【问题标题】:creating a loop to convert elements of a matrix in matlab在matlab中创建一个循环来转换矩阵的元素
【发布时间】:2020-10-26 20:15:55
【问题描述】:

问题:创建一个名为 checkflip 的支票副本。然后,创建一个循环,如果 checkflip 的每个元素的值为 0,则将其转换为 1,如果其值为 1,则将其转换为 0。循环中的代码一次只能对 checkflip 的一个元素进行操作

在之前的问题中,我在下面的代码中建立了检查:

x=[0 1]; 
y=x([2 1]);  
check=repmat([repmat(y,1,4);repmat(x,1,4)], 4, 1); 

我尝试了下面的代码来解决我的问题,但它似乎没有做任何事情,我不知道为什么

checkflip=check; 
x=checkflip; 
for i=1:8
    if x(i)==0
        x(i)=1; 
    elseif x(i)==1
        x(i)=0; 
    end 
end 

【问题讨论】:

  • 我认为最好直接在循环内对checkflip 进行操作。还要检查一个可能需要 2 个索引变量的二维数组。
  • 否则,您需要跨/最多 64 个元素运行循环。

标签: matlab loops matrix


【解决方案1】:

使用~ 取补是一种使用一组 for 循环翻转矩阵中每个值的选项。一组两个 for 循环可用于 1 到 1 遍历数组的每个索引。外部 for 循环控制对行的扫描,内部 for 循环控制对列的扫描。或者,方法 3 显示了如何使用单个循环并相应地评估相应的 row (i)column (j)。小心连续的 if 语句很重要,因为有时在第一个 if 语句的主体内 checkflip 可能会翻转,导致第二个 if 语句意外触发。有时最好不要在连续的 if 语句及其主体中涉及相同的变量。

编辑:或者,您可以使用一个从 1 到数组元素数的 for 循环,在这种情况下为 64,因为 MATLAB 通过从左到右遍历行来索引数组。

循环方法:

下面显示了 5 x 5 数组/矩阵的循环方法,但这可以很容易地扩展到任何大小的数组/矩阵。

方法一:使用补码

x=[0 1]; 
y=x([2 1]);  
check = repmat([repmat(y,1,4);repmat(x,1,4)], 4, 1); 


checkflip = check; 

for i = 1: 8
   for j = 1: 8 
       
 checkflip(i,j) = ~checkflip(i,j);
       
   end
end

x=[0 1]; 
y=x([2 1]);  
check = repmat([repmat(y,1,4);repmat(x,1,4)], 4, 1); 
checkflip = check; 

for i = 1: 64   
 checkflip(i) = ~checkflip(i);
end

方法 2:使用 If 语句

x=[0 1]; 
y=x([2 1]);  
check = repmat([repmat(y,1,4);repmat(x,1,4)], 4, 1); 


checkflip = check; 

for i = 1: 8
   for j = 1: 8 
       
 if(checkflip(i,j) == 0)
     Result = 1; 
 end
           
 if(checkflip(i,j) == 1)
     Result = 0;
 end
     
 checkflip(i,j) = Result;
 
   end
end

方法 3:仅限于一个循环

x=[0 1]; 
y=x([2 1]);  
check = repmat([repmat(y,1,4);repmat(x,1,4)], 4, 1); 

checkflip = check; 

i = 1;
j = 0;
for Loop = 1: 64
j = j + 1;
    
    if(j > 8)
    j = 1;
    i = i + 1;
    end
        
 if(checkflip(i,j) == 0)
     Result = 1; 
 end
           
 if(checkflip(i,j) == 1)
     Result = 0;
 end
     
 checkflip(i,j) = Result;
 
end

编辑:@David 建议的一个很好的解决方案是使用函数 numel() 无缝地遍历所有数组元素:

x=[0 1]; 
y=x([2 1]);  
check = repmat([repmat(y,1,4);repmat(x,1,4)], 4, 1); 

checkflip = check; 
for i=1:numel(checkflip)
    
checkflip(i) = ~checkflip(i);

end

扩展:没有循环(问题除外,所有元素一次)

x=[0 1]; 
y=x([2 1]);  
check = repmat([repmat(y,1,4);repmat(x,1,4)], 4, 1); 
checkflip = double(~check);

使用 MATLAB R2019b 运行

【讨论】:

  • 您的方法 3 过于复杂。你可以只做for i=1:numel(checkflip); checkflip(i), ...,end 来遍历checkflip 的每个元素。
  • 很好,抓住!谢谢你的提示。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-02
  • 1970-01-01
  • 2016-11-27
  • 2013-03-14
相关资源
最近更新 更多