File Exchange

image thumbnail

if-then-else shortcut

version 1.1.0.0 (1.5 KB) by Yanai
The function is a shortcut for simple if conditions, to reduce redundant code

1 Download

Updated 31 Aug 2010

View License

shortcut for simple if conditions.
The function works similar to Excel format.
First argument is the condition, second is what to do if true, third is what to do if false.

example 1:
A = ifelse(x>thr, 5, 3)
will execute:
if x>thr
A = 5
else
A = 3
end

example 2:
A = ifelse(im>thr, im*2, im/2)
will execute:
A = im*2 where im>thr
A = im/2 where im<=thr

example 3:
ifelse(x~=0, 'y=1/x;', 'disp ''x is zero''')
will execute:
if x~=0
y = 1/x;
else
disp 'x is zero'
end

Cite As

Yanai (2020). if-then-else shortcut (https://www.mathworks.com/matlabcentral/fileexchange/28587-if-then-else-shortcut), MATLAB Central File Exchange. Retrieved .

Comments and Ratings (3)

Tudor

Yanai

Thanks Oleg for you comment.
Regarding the 2nd example you wrote, I agree I should have returned an error, since there is no meaning in using non-scalars as condition, and an expression as result.

In the 1st example, the behavior is required IMO, but maybe the documentation is lacking. If x is non-scalar there are two possible uses:
1) as I wrote in my example2 (all inputs are non-scalars)
2) result is 5 where x>thr, and 3 elsewhere

Oleg Komarov

I bring to the attention this behaviour:

ifelse([10,1] > 2,1,0)
ans =
1 0

ifelse([10,1] > 2,'a = 1','b = 0')
b =
0

As you can see its behaviour depends not on the first input (and on its features, a double row vector) but rather on the second and third argument.
This is totally unexpected and IMO unwanted.

This kind of problem is evident from the wrong "example 1". If x is not a scalar then the if-else construct doesn't describe what the function does.

Updates

1.1.0.0

added another option to function (example 2 in description).

MATLAB Release Compatibility
Created with R2008b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Tags Add Tags