MATLAB Answers

# if else in a loop

조회 수: 1(최근 30일)
Stephen Devlin 2018년 1월 16일
댓글: Stephen Devlin 2018년 1월 16일
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

댓글을 달려면 로그인하십시오.

### 채택된 답변

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표시숨기기 없음
Stephen Devlin 2018년 1월 16일
Ah, so if I'd used dismember and got a logical 1 I could then have used that, sorry. For some reason 'if modn==2|4' looks like it made sense to me but I didn't appreciate the precedence rules etc. Thank you Walter.

댓글을 달려면 로그인하십시오.

### 추가 답변(1개)

Stephen Cobeldick 2018년 1월 16일
편집: Stephen Cobeldick 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
##### 댓글 수: 2표시숨기기 이전 댓글 수: 1
Stephen Devlin 2018년 1월 16일
Thank you Stephen, this works perfectly.

댓글을 달려면 로그인하십시오.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!