MATLAB: Simple if/else logic in MATLAB

conditional statementsif else

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

Best Answer

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.
Related Question