How to use if statement for than one variables?
5 views (last 30 days)
Show older comments
Ivan Mich
on 4 Jul 2021
Edited: Sulaymon Eshkabilov
on 4 Jul 2021
I would like to set one if statement. I am using the following code:
filename2= 'OutputFile1L.xlsx';
[d2,tex]= xlsread(filename2);
a=d2(:,1);
for ii=1:numel(a)
if a(ii)==0
b(ii)==1 & c(ii)==0
elseif a(ii)==1
b(ii)==0 & c(ii)==0
elseif a==2
b(ii)==0 & c(ii)==0
else
b(ii)==nan & c(ii)==nan
end
but command window shows me
Undefined function or variable b
What is the wrong? could you please help me?
0 Comments
Accepted Answer
Sulaymon Eshkabilov
on 4 Jul 2021
Edited: Sulaymon Eshkabilov
on 4 Jul 2021
Note that for loop and "if" based calcs are very slow and inefficient.
Anyhow if indeed you wish to fix your code, then check these corrected errs with ==, & |, , e.g:
for ii=1:numel(a)
if a(ii)==0
b(ii)=1; c(ii)=0;
elseif a(ii)==1 | a(ii)==2
b(ii)=0; c(ii)=0;
else
b(ii)=nan; c(ii)=nan;
end
end
2 Comments
Sulaymon Eshkabilov
on 4 Jul 2021
@Image Analyst Very Good point and discussion! "Not Always" cases are small size simulation problems which require insignifcantly small amount of sim time.
More Answers (2)
Yongjian Feng
on 4 Jul 2021
You meant this?
if a(ii)==0
b(ii)=1;
c(ii)=0;
elseif a(ii)==1
b(ii)=0;
c(ii)=0;
elseif a==2
b(ii)=0;
c(ii)=0;
else
b(ii)=nan;
c(ii)=nan;
end
1 Comment
Sulaymon Eshkabilov
on 4 Jul 2021
Edited: Sulaymon Eshkabilov
on 4 Jul 2021
There are a couple of ERRs in Feng's proposed code:
for ... % is missing
...
if ..
elseif a==2 % MUST be a(ii)==2
...
end
end
Sulaymon Eshkabilov
on 4 Jul 2021
Edited: Sulaymon Eshkabilov
on 4 Jul 2021
There are several errs in your loop code that is not advised. Just because it is slow and inefficient.
Here is an easy sol isntead of loop based code:
...
a=d2(:,1);
Idx0=find(a(:)==0);
Idx1=find(a(:)==1 | a(:)==2);
Idx2=find(a~=0 & a~=1 & a~=2);
b(Idx0)=1; c(Idx0)=0;
b(Idx1)=0; c(Idx1)=1;
b(Idx2)=nan; c(Idx2)=nan;
0 Comments
See Also
Categories
Find more on Operators and Elementary Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!