MATLAB Answers

In switch-case, case values from variable (dynamic)

43 views (last 30 days)
array1 = [1 2 3]; % this will change in the program
array2 = [4 5 6]; % this will change in the program
switch anyVariable
case {array1}
disp('1')
case {array2}
disp('2')
otherwise
disp('3')
end
This always displays 3, irrespective of the value of anyVariable. Shall I change it to if-elseif kind structure?

  0 Comments

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 31 May 2018
Edited: Stephen Cobeldick on 31 May 2018
Use cell arrays, where each cell contains one scalar numeric (or a char vector):
V1 = {1,2,3};
V2 = {4,5,6};
switch scalarVal
case V1
disp('one')
case V2
disp('two')
otherwise
disp('none')
end

  7 Comments

Show 4 older comments
Walter Roberson
Walter Roberson on 31 May 2018
It appears that it rejects vectors and arrays except for character vectors.
Pramit Biswas
Pramit Biswas on 1 Jun 2018
Only after viewing the comment I tried to execute that (Thanks for the comment). It can be a nice feature to add.
Stephen Cobeldick
Stephen Cobeldick on 1 Jun 2018
@Pramit Biswas: you can convert numeric row vectors to char (as long as they are suitable, i.e. positive integers, etc).

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Products


Translated by