My if statement with multiple conditions gives wrong values

I have an if-statement in a double for-loop, where I want to get some certain values ('triangles') out, like this:
for j = jsweep(sweep,1):jsweep(sweep,3):jsweep(sweep,2);
for i = isweep(sweep,1):isweep(sweep,3):isweep(sweep,2);
if onsrc(i,j) == false;
tt_locmin = init_tt;
if (((1 < i) && (i < nx)) && ((1 < j) && (j < ny)))
triangles = [1,2,3,4,5,6,7,8];
elseif ((i == 1) && (j == 1))
triangles = [3,4];
elseif ((i == nx) && (j == 1))
traingles = [1,2];
elseif ((i == 1) && (j == ny))
triangles = [5,6];
elseif ((i == nx) && (j == ny))
triangles = [7,8];
elseif ((j < ny) && (i == 1))
triangles = [3,4,5,6];
elseif ((j < ny) && (i == nx))
triangles = [1,2,7,8];
elseif ((i < nx) && (j == 1))
triangles = [1,2,3,4];
elseif ((j == ny) && (i < nx))
triangles = [5,6,7,8];
end
end
end
But I can't seem to get the right values of 'triangles' out. When the loop reaches i = nx, j = 1, it still gives me the values triangles = [1, 2, 3, 4], where it should give me triangles = [1, 2]. What is wrong?

댓글 수: 1

You are overwriting triangles in every iteration of the loop, so the end result is going to be whatever was computed on the last iteration.
How is nx being calculated? I hypothesize that you might have calculated it using floating point values instead of as an integer: if so then you could be suffering from round-off error.

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

답변 (2개)

Roger Stafford
Roger Stafford 2017년 11월 17일

1 개 추천

Could it be because you have misspelled 'triangles' as 'traingles' at that point?

댓글 수: 2

I didn't see this coming! Good catch Roger!
Just realized this as well, but it did not fixed the problem. I pre-allocated the triangles, which solved the main problem. But nice catch ;)

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

KL
KL 2017년 11월 17일
편집: KL 2017년 11월 17일
Store the output of every iteration of triangles in a cell array. For example,
traingles = cell(desiredSize); %pre-allocate properly
then in the for loop,
triangles{i,j} = [1,2] or [1,2,3,4]
For your problem, I'd suspect triangles value is unchanged from its previous iteration (from when (i < nx) && (j == 1)). Possibly the outer if loop condition | onsrc(i,j) == false| is not satisfied and hence you don't go inside the internal if-elseif statements.
This is why pre-allocating and storing the result everytime would help figure out the reason why it happens.
one additional tip: try not to use i and j as iterating variables in matlab because they are the default imaginary units here. It may not cause trouble now but better to avoid them as a best practice.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2017년 11월 17일

댓글:

2017년 11월 17일

Community Treasure Hunt

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

Start Hunting!

Translated by