Why the loop still run after get to the of the array
조회 수: 1 (최근 30일)
이전 댓글 표시
I am trying to diaplay a true table with 1 stand for true, 0 stand for false and 2 for maybe.
two array when x is o, or y is 0, display 0 directly and return; if x=1 and y=1 display 1(true); if x=1 and y=2 display 2(maybe); if x=2 and y=1 then display 2(maybe)
here is my code, I know that might be the best way to do it so if you had a better way please advise.
For now I don't know why the loop still keep going after it reach to the end of the array. Please let me know if you know what is wrong. Thank you in advance.
clc;clear;
%create arrays
x=[1 1 1 0 0 0 2 2 2];
y=[1 0 2 1 0 2 1 0 1];
for i=1:length(x)
for r=1:length(y)
if x(i)==0
disp('0');
elseif x(i)==y(i)==1
disp('1');
elseif x(i)==1 && y(i)==2
disp('2');
elseif x(i)==2 && y(i)~=0
disp('2');
else
disp('0');
end
i=i+1;
end
end
%Here is what in the command window; but i only expect 9 digits
1
0
2
0
0
0
2
0
2
0
2
0
0
0
2
0
2
Index exceeds the number of array elements (9).
Error in test_q22 (line 13)
if x(i)==0
댓글 수: 0
채택된 답변
Mehmed Saad
2020년 4월 11일
With Your Code (For Loops)
clc;clear;
%create arrays
x=[1 1 1 0 0 0 2 2 2];
y=[1 0 2 1 0 2 1 0 1];
for i=1:length(x)
%Not required
% for r=1:length(y)
if x(i)==0
disp('0');
elseif x(i)==y(i)==1
disp('1');
elseif x(i)==1 && y(i)==2
disp('2');
elseif x(i)==2 && y(i)~=0
disp('2');
else
disp('0');
end
% Not required
% i=i+1;
% end
end
Short Method (array)
tr_t =1*((x==1)&(y==1))+2*((x+y)>2);
disp(num2str(tr_t'));
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Cell Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!