代码报错,如何优化。

3 次查看(过去 30 天)
fsyrkvy
fsyrkvy 2023-5-22
回答: npcced 2023-5-22
报错: Index in position 1 exceeds array bounds. Index must not exceed 5.
a = [2,1,2,0,2,1,1,0,0,0,0,2,1,1;
1,2,0,2,2,1,1,1,2,2,0,2,2,2;
0,0,2,2,0,1,2,0,0,1,1,1,2,0;
1,0,0,2,0,0,0,0,1,1,1,2,1,1;
1,1,0,2,2,2,0,1,1,0,0,0,2,0;];
out = zeros(5,10);
for i=1:6 %循环行处理
j=1; %每行逐个元素处理
flag=a(i,j); %获取参照元素
count=1;
outi=1; %输出矩阵B列号
while j<14 %各行循环列处理
j=j+1;
if flag==a(i,j);
count=count+1;
else %重置计数并输出结果到out
out(i,outi)=count;
count=1;
outi=outi+1;
flag=a(i,j);
end
if j==14 %对最后一个元素进行处理
out(i,outi)= count;
end
end
end

采纳的回答

npcced
npcced 2023-5-22
仅供参考
a = [2,1,2,0,2,1,1,0,0,0,0,2,1,1;
1,2,0,2,2,1,1,1,2,2,0,2,2,2;
0,0,2,2,0,1,2,0,0,1,1,1,2,0;
1,0,0,2,0,0,0,0,1,1,1,2,1,1;
1,1,0,2,2,2,0,1,1,0,0,0,2,0;];
out = zeros(5,10);
for i=1:5   %循环行处理
   j=1;     %每行逐个元素处理
   flag=a(i,j);  %获取参照元素
count=1;     
outi=1;  %输出矩阵B列号
  while j<14    %各行循环列处理
      j=j+1;
      if flag==a(i,j)
            count=count+1;
           
      else    %重置计数并输出结果到out            
out(i,outi)=count;
            count=1;  
            outi=outi+1;
            flag=a(i,j);
      end
      if  j==14    %对最后一个元素进行处理
           out(i,outi)= count;
      end
    end   
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!