if else in a loop
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2018-1-16
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.
更多回答(1 个)
Stephen23
2018-1-16
编辑:Stephen23
2018-1-16
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!