0

I would like to get something like this in Matlab:

x = round(rand*10);
switch (x)
    case {0:10}
        disp('x between 0 and 10');
    case {11:20}
        disp('x between 11 and 20');
    case {21:100}
        disp('x between 21 and 100');
end

But unfortunately it doesn't work. Don't enter in any of the cases. Do you know how can I do that?

3 Answers 3

4

A little simple than Luis Mendo's Answer, just use num2cell to convert your matrix of doubles into a cell array of doubles.

x = randi(100);

switch (x)
    case num2cell(0:10)
        disp('x between 0 and 10');
    case num2cell(11:20)
        disp('x between 11 and 20');
    case num2cell(21:100)
        disp('x between 21 and 100');
end
Sign up to request clarification or add additional context in comments.

1 Comment

+1 I always forget that num2cell automatically picks entries one by one
3

The problem is that {0:10} is not {0,1,...,10}, but rather {[0,1,...,10]}. So it's a single cell containing a vector, and of course x never equals that vector.

To solve it, use cell arrays with one element per cell. To create them from vectors you can use mat2cell (or better yet num2cell, as in @thewaywewalk's answer)

x = round(rand*10);
switch (x)
    case mat2cell(0:10,1,ones(1,11))
        disp('x between 0 and 10');
    case mat2cell(11:20,1,ones(1,11))
        disp('x between 11 and 20');
    case mat2cell(21:100,1,ones(1,81))
        disp('x between 21 and 100');
end

Or, more easily, use elseifs instead of switch, and then you can use vectors and any:

x = round(rand*10);
if any(x==0:10)
    disp('x between 0 and 10');
elseif any(x==11:20)
    disp('x between 11 and 20');
elseif any(x==21:80)
    disp('x between 21 and 100');
end

Comments

0

Much cleaner solution is to set switch to true. I use this approach all the time given that the "switch" construction is easier to read than the "if then else" construction.

For example:

i = randi(100);
switch true
    case any(i==1:50)
        statement
    case any(i==51:100)
        statement
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.