if else in a loop
Mostrar comentarios más antiguos
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
Respuesta aceptada
Más respuestas (1)
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
Categorías
Más información sobre Logical en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!