
Flow control: for and switch
For-looping without index
The syntax of
for i = 1:10
... % Something wonderful here
end
and it it easy to forget that the index vector
>> 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
Comparing against multiple values in switch
The
% 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
Comments
There are no comments on this post so far. Write a comment.