My if statement with multiple conditions gives wrong values
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commento
Walter Roberson
il 17 Nov 2017
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.
Risposte (2)
Roger Stafford
il 17 Nov 2017
Could it be because you have misspelled 'triangles' as 'traingles' at that point?
2 Commenti
KL
il 17 Nov 2017
Modificato: KL
il 17 Nov 2017
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.
Vedere anche
Categorie
Scopri di più su Performance and Memory in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!