if else in a loop
1 view (last 30 days)
Show older comments
Stephen Devlin
on 16 Jan 2018
Commented: Stephen Devlin
on 16 Jan 2018
Hi, I have a variable extracted from a filename that I need to use to map the data in that file to a location in a big data set so that I can plot the whole dataset. The variable is a location variable. However it takes the range 1 to 4, and is also dependant on another value extracted from the filename for its final location in the dataset.
modules 1&3 are in a straight line, modules 2&4 are behind 1&3 and offset to lay between them
4_2.
_3_1
arrangement. Anyway, the problem should be easier to see in the code...
name={'Y1Z1','Y1Z3','Y2Z2','Y2Z4','Y3Z1','Y3Z3','Y4Z2','Y4Z4'}
Sizzy=size(name)
S=Sizzy(1,2)
rowCount=nan(S,1)
for k=1:S
A=name{k};
modn=str2double(A(1,2));
rown=str2double(A(1,4));
if modn==2|4
rown==rown+4
else modn==1|3
rown==rown
end
rowCount(k)=rown
end
which gives
rowCount =
1.00 3.00 2.00 4.00 1.00 3.00 2.00 4.00
whereas I need
rowCount =
1.00 3.00 6.00 8.00 1.00 3.00 6.00 8.00
I think the problem is with my if if else statement, maybe a misuse of the logical or, but I cannot see what I am doing wrong.
Best regards,
Steve
0 Comments
Accepted Answer
Walter Roberson
on 16 Jan 2018
if modn==2|4
means the same as
if ((modn==2)|4)
The result of the modn==2 test is either 0 (false) or 1 (true), and you then or() that 0 or 1 with 4. 4 is a non-zero value so it is considered true, 1. You are therefore or() 0 or 1 with 1, and the results of that will always be true.
I am not aware of any computer language that has a comparison operation in the form you gave.
MATLAB's test to determine whether a value is any of a list of values is the ismember() function.
More Answers (1)
Stephen23
on 16 Jan 2018
Edited: Stephen23
on 16 Jan 2018
This syntax does not do what you think it does:
modn==2|4
MATLAB will execute these from left to right, giving:
(modn==2)|4
equivalent to:
0|4 or 1|4
which will clearly always be true (any non-zero value is true in MATLAB, so 4 is clearly true).
Read more about the sequence of operations here:
You might like to try something like this:
name = {'Y1Z1','Y1Z3','Y2Z2','Y2Z4','Y3Z1','Y3Z3','Y4Z2','Y4Z4'};
S = numel(name);
Z = nan(S,1);
for k = 1:S
A = name{k};
modn = str2double(A(2));
rown = str2double(A(4));
Z(k) = rown + 4*~mod(modn,2);
end
See Also
Categories
Find more on Logical 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!