Matlab syntax tricks

By Raphaël - December 18th, 2016

Matlab

0 Comment

Structures
Packages

# Flow control: for and switch

## For-looping without index

The syntax of for loops often ressembles:

for i = 1:10

...  % Something wonderful here

end

and it it easy to forget that the index vector 1:10 can be replaced by any other vector. For instance, it is perfectly possible to use a string instead, as it is an array like an other array:

>> for c = 'Hello', disp(c); end
H
e
l
l
o

Or, even better, one can iterate directly over structures or cells:

>> for a = {'hello' 'world'}, a{:}, end

ans =

hello

ans =

world

With this syntax there is no index anymore, but for many simple loops this is not really a big deal. The code is simpler, and one skips a call to numel to determine the size of the array / structure / cell to walk through.

## Comparing against multiple values in switch

The switch statement allows one to execute a piece of code depending on a case expression. Interestingly, Matlab allows to compare against multiple numbers, strings or mixed elements at once:

% Get some user input
in = input('Please type something: ', 's');

% Try to cast the input (char) into a number
if ~isnan(str2double(in)), in = str2double(in); end

switch in

case 0                            % Compare against a number
disp('You entered 0');

case 'banana'                     % Compare against a string
disp('Sorry, no more banana');

case {1, 'one', 'unity'}          % Compare against multiple and mixed elements
disp('You entered 1');

otherwise                         % Default behavior
disp('Hu?')

end
Structures
Packages