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?

 채택된 답변

Stephen23
Stephen23 2018년 5월 31일
편집: Stephen23 2018년 5월 31일

0 개 추천

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

Unless, that is, anyVariable is a vector and you want to compare the entire vector for equality with array1 or array2
Aha, I missed it... Thank you. I used num2cell(array1): (This is just for reference)
For the comment, is it possible to compare vector (numeric, not character), e.g.: switch [4 5 6]?
"For objects that support the eq function, case_expression == switch_expression."
That said, I would want to test to be sure.
It appears that it rejects vectors and arrays except for character vectors.
Only after viewing the comment I tried to execute that (Thanks for the comment). It can be a nice feature to add.
@Pramit Biswas: you can convert numeric row vectors to char (as long as they are suitable, i.e. positive integers, etc).

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

태그

질문:

2018년 5월 31일

댓글:

2018년 6월 1일

Community Treasure Hunt

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

Start Hunting!

Translated by