Matlab 在单元格数组中指定多个值

Matlab 在单元格数组中指定多个值,matlab,Matlab,我有以下重复代码(if语句): aaa=小区(3,1); aaa={rand(20,1);rand(20,1);rand(20,1)}; bbb=细胞(3,1); 对于ii=1:20 if(aaa{1,1}(ii,1)有时,稍微长一点的代码(如您的代码)更容易阅读,最终也更容易调试。也就是说,这是一个没有任何显式for或if语句的解决方案。有些人可能认为这是隐式完成的 ccc = cell(3,1); tempmat = [ones(20, 1) zeros(20, 2)]; %This ini

我有以下重复代码(if语句):

aaa=小区(3,1);
aaa={rand(20,1);rand(20,1);rand(20,1)};
bbb=细胞(3,1);
对于ii=1:20

if(aaa{1,1}(ii,1)有时,稍微长一点的代码(如您的代码)更容易阅读,最终也更容易调试。也就是说,这是一个没有任何显式for或if语句的解决方案。有些人可能认为这是隐式完成的

ccc = cell(3,1);
tempmat = [ones(20, 1) zeros(20, 2)]; %This initializes the else part of your ifs
ccc = {tempmat; tempmat; tempmat};

ind1 = find(aaa{1,1} < 0.5); %Finds all the cases when aaa is less than 0.5
ind2 = find(aaa{2,1} < 0.5);
ind3 = find(aaa{3,1} < 0.5);

ccc{1,1}(ind1,:) = repmat([0 1 0], length(ind1), 1);
ccc{2,1}(ind2,:) = repmat([0 1 0], length(ind2), 1);
ccc{3,1}(ind3,:) = repmat([0 1 0], length(ind3), 1);
ccc=cell(3,1);
tempmat=[one(20,1)zero(20,2)];%这将初始化ifs的else部分
ccc={tempmat;tempmat;tempmat};
ind1=find(aaa{1,1}<0.5);%查找aaa小于0.5时的所有情况
ind2=find(aaa{2,1}<0.5);
ind3=find(aaa{3,1}<0.5);
ccc{1,1}(ind1,:)=repmat([0110],length(ind1),1);
ccc{2,1}(ind2,:)=repmat([0110],length(ind2),1);
ccc{3,1}(ind3,:)=repmat([0110],length(ind3),1);

您真的需要使用单元格数组吗?2D数组似乎更适合您的数据,可以让您避免if,甚至可能避免循环easily@LuisMendo我确实不需要细胞阵列。
ccc = cell(3,1);
tempmat = [ones(20, 1) zeros(20, 2)]; %This initializes the else part of your ifs
ccc = {tempmat; tempmat; tempmat};

ind1 = find(aaa{1,1} < 0.5); %Finds all the cases when aaa is less than 0.5
ind2 = find(aaa{2,1} < 0.5);
ind3 = find(aaa{3,1} < 0.5);

ccc{1,1}(ind1,:) = repmat([0 1 0], length(ind1), 1);
ccc{2,1}(ind2,:) = repmat([0 1 0], length(ind2), 1);
ccc{3,1}(ind3,:) = repmat([0 1 0], length(ind3), 1);