Why the loop still run after get to the of the array

1 view (last 30 days)
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

Accepted Answer

Mehmed Saad
Mehmed Saad on 11 Apr 2020
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'));

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!