Simple if/else logic in MATLAB

26 ビュー (過去 30 日間)
Sas
Sas 2011 年 3 月 18 日
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

採用された回答

Jan
Jan 2011 年 3 月 18 日
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 件のコメント
Sas
Sas 2011 年 3 月 18 日
Ah yes you're absolutely right! I was up doing this late for a lab assignment - I knew it was something silly.
Thanks very much!
Jan
Jan 2011 年 3 月 18 日
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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeDescriptive Statistics and Visualization についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by