Hi Everyone, I need your help on my problem.

1 view (last 30 days)
I have a 3D matrix (abc), and I need to do if and elseif conditions to this matrix. However, the only the first expression(aa=abc-5) is applied to all elements. %
if 1<abc<=5
elseif 6<abc<=10
How can I make the elseif expression work?
Thank you.

Accepted Answer

Jan on 7 Mar 2018
Edited: Jan on 7 Mar 2018
1 < abc <= 5
This will not do, what you expect. Matlab processes this expression from left to right:
  1. 1 < abc. This is either TRUE or FALSE, which is interpreted as 1 or 0
  2. 1 <= 5 or 0 <= 5. This is TRUE in both cases.
You want:
1 < abc && abc <= 5
Then your if and elseif will work.
For productive code using logical indexing as suggested by Birdman is usually more efficient and nicer. But understanding why a<b<c fails is essential.
Engdaw Chane
Engdaw Chane on 7 Mar 2018
@Jan This was what I have been looking for. The others also work but I wasn't getting the dimensions I needed because of a reason in my code. Thank you.

Sign in to comment.

More Answers (1)

Birdman on 7 Mar 2018
Edited: Birdman on 7 Mar 2018
Actually, you do not need a ifelse statement. Simple logical indexing will give you what you want.
abc(abc>1 & abc<=5)=abc(abc>1 & abc<=5)-5;
abc(abc>6 & abc<=10)=abc(abc>6 & abc<=10)+10
Walter Roberson
Walter Roberson on 7 Mar 2018
If the inputs are certain to be in that range then you can simplify to
mask = Hx20_50 <= 0.5;
t20_50(mask) = sqrt(log(1./(Hx20_50(mask).^2)));
t20_50(~mask) = sqrt(log(1./(1-Hx20_50(~mask)).^2));

Sign in to comment.


Find more on Resizing and Reshaping Matrices 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!