代码报错,如何优化。

조회 수: 4 (최근 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!