image thumbnail

if-then-else shortcut

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


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
A = 3

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;
disp 'x is zero'

Cite As

Yanai (2022). if-then-else shortcut (, MATLAB Central File Exchange. Retrieved .

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

Community Treasure Hunt

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

Start Hunting!