# why if elseif statement is not working

11 views (last 30 days)
safi58 on 12 Nov 2021
Commented: safi58 on 28 Nov 2021
Hi,
I have this following code and attached data. only if statement is working but not the rest. can any please help?
clc
clear all
va=numdata(:,1);
vb=numdata(:,2);
vc=numdata(:,3);
for i=1:length(va)
if((va(i)>207 | va(i) <253) &(vb(i)>207 | vb(i)<253) & (vc(i)>207 | vc(i)<253))
ma(i)=1;
mb(i)=1;
mc(i)=1;
elseif ((va(i)>253 | va(i) <260)&(vb(i)>253 | vb(i)<260)&(vc(i)>253 | vc(i)<260))
ma(i)=(260-va(i))/(260-253)
mb(i)=(260-vb(i))/(260-253);
mc(i)=(260-vc(i))/(260-253);
elseif ((va(i)>260)&& (vb(i)>260)&& (vc(i)>260))
ma(i)=0;
mb(i)=0;
mc(i)=0;
end
pmax=5000;
pa(i)=ma(i).*pmax;
pb(i)=mb(i).*pmax;
pc(i)=mc(i).*pmax;
plot(pa)
end

Dave B on 12 Nov 2021
This expression:
va(i)>207 | va(i) <253
asks whether the value is greater than 207 or less than 253. All values (other than NaN) are greater than 207 or less than 253.
I'm going to guess a bit at the logic, and suspect you want AND instead of OR here?
if (va(i)>207 && va(i)<253) && (vb(i)>207 && vb(i)<253) && (vc(i)>207 && vc(i)<253)
and similar logic for the other two statements.
Alternatively, do this the MATLAB way and use a matrix (and we might as well take advantage of readmatrix along the way).
m=nan(size(v));
m(all(v>207 & v<253,2),:)=1;
m(all(v>260,2),:)=0;
ind = all(v>253 & v<260,2);
m(ind,:)=(260-v(ind,:)) / (260-253);
p = m*5000;
nexttile;plot(p)
Note 1: Several values not accounted for here: anything less than or equal to 207, as well as values exactly equal to 253 or 260, and rows of v (place where va, vb, cv) are not all in the same category.
Note 2: This looks like you wanted to flip the data and rescale it, if that's your goal there's an easy way (see rescale), and if the flip was not your intention just remove ther "5000-":
pp = 5000-rescale(v,0,5000,'InputMin',253,'InputMax',260);
nexttile;plot(pp) safi58 on 28 Nov 2021
Hi Dave,
I think it would be better if it could be done on value by value basis. in that case latter one should be ok.

DGM on 12 Nov 2021
Edited: DGM on 12 Nov 2021
It's doing exactly what you're telling it to do. Look at the range of the data. Look at the logical tests you're doing. Case 1 and 2 are always true.
I'm assuming this is closer to what you're trying to do:
pmax = 5000;
% v contains all three vectors [va vb vc]
th = [207 253 260];
% m contains all three vectors [ma mb mc]
m = zeros(size(v,1),3);
m(mask(:,3),:) = 0; % possibly redundant
% p contains all three vectors [pa pb pc]
p = m*pmax;
plot(p) Otherwise, you'll have to clarify what the logical comparisons should be.
safi58 on 12 Nov 2021
Hi DGM, really appreciate your help.