Simple if/else logic in MATLAB
23 views (last 30 days)
Show older comments
Hi there, I've been working on a piece of code for calculating voltage and electric field inside coaxial cables of different sizes.
While doing my computation, I needed to do an if/else statement and was boggled as to why these two versions of the statement did not work interchangeably. For reference, both these statements are executed in a nested for loop (i, j are declared - there is no syntax error - just a logic one).
Option 1:
if ((i < innerstartx) || (i > innerendx) || (j < innerstarty) || (j > innerendy))
V(i,j) = (V(i+1,j) + V(i-1,j) + V(i,j+1) + V(1,j-1))/4;
else
end
Option 2:
if (i>=innerstartx && i<=innerendx && j>=innerstarty && j<=innerendy)
else
V(i,j)=0.25*(V(i+1,j)+V(i-1,j)+V(i,j+1)+V(i,j-1));
end
Currently, option 2 works, but option 1 doesn't. I checked over the logic a few times and I am pretty sure it is sound (simply De Morgan's inversion).
I was just curious though, as I'd like to be able to avoid this sort of problem should it arise in the future.
Thanks for your help.
sas
0 Comments
Accepted Answer
Jan
on 18 Mar 2011
As far as I can see the logic is ok. You can test it manually by inserting a check in the code:
if ~isequal( ...
not(i < innerstartx || i > innerendx || ...
j < innerstarty || j > innerendy), ...
(i >= innerstartx && i <= innerendx && ...
j >= innerstarty && j <= innerendy))
error('Fail!');
end
But these lines differ:
V(i,j) = (V(i+1,j) + V(i-1,j) + V(i,j+1) + V(1,j-1)) / 4;
V(i,j) = (V(i+1,j) + V(i-1,j) + V(i,j+1) + V(i,j-1)) * 0.25;
^
The last V term uses "1" in the option 1 version, but "i" in the option 2.
2 Comments
Jan
on 18 Mar 2011
Confusing i, 1 and l or 0 and O is a standard problem. But after 32 years of programming my eyes get worse and my mind is alerted whenever something appears on the screen, which looks like a small fly from a distance.
More Answers (0)
See Also
Categories
Find more on Descriptive Statistics and Visualization in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!