My if statement with multiple conditions gives wrong values

2 ビュー (過去 30 日間)
Thea_Q
Thea_Q 2017 年 11 月 17 日
コメント済み: Thea_Q 2017 年 11 月 17 日
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 件のコメント
Walter Roberson
Walter Roberson 2017 年 11 月 17 日
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 日
Could it be because you have misspelled 'triangles' as 'traingles' at that point?
  2 件のコメント
KL
KL 2017 年 11 月 17 日
I didn't see this coming! Good catch Roger!
Thea_Q
Thea_Q 2017 年 11 月 17 日
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.

カテゴリ

Help Center および File ExchangePerformance and Memory についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by