My if statement with multiple conditions gives wrong values
2 次查看(过去 30 天)
显示 更早的评论
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
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
2017-11-17
Could it be because you have misspelled 'triangles' as 'traingles' at that point?
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 Exchange 中查找有关 Performance and Memory 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!