Switch-case function problem

조회 수: 15 (최근 30일)
Skomantas Tamulaitis
Skomantas Tamulaitis 2020년 10월 16일
댓글: Skomantas Tamulaitis 2020년 10월 16일
Hello, I am trying to get the values of the vector color to be displayed as 0 = yellow; 1 = red; 2 = green;
3 = blue; using switch-case function. I got this but it doesn't work.
color=[2,1,3,0,1,3,1,0,2]
cName ={'yellow','red','green','blue'};
for ind=1:length(color)
switch ind
case color ==0
disp(cName{'yellow'});
case color==1
disp(cName{'red'});
case color==2
disp(cName{'green'});
case color== 3
disp(cName{'blue'});
end
end
Could someone help me with this?
THANKS!

채택된 답변

Steve Eddins
Steve Eddins 2020년 10월 16일
First variation: fix the switch and case lines and the indexing into cName.
switch color(ind)
case 0
disp(cName{ind+1});
case 1
disp(cName{ind+2});
Second variation: dispense with the switch statement altogether.
color=[2,1,3,0,1,3,1,0,2]
cName ={'yellow','red','green','blue'};
for ind=1:length(color)
disp(cName{color(ind)+1})
end
Third variation: use a string array instead of a cell array of char vectors. This is the modern way to handle text in MATLAB.
color=[2,1,3,0,1,3,1,0,2]
cName = ["yellow", "red", "green", "blue"];
for ind=1:length(color)
disp(cName(color(ind)+1))
end
  댓글 수: 1
Skomantas Tamulaitis
Skomantas Tamulaitis 2020년 10월 16일
Very informative, THANK YOU!

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

추가 답변 (1개)

Johannes Hougaard
Johannes Hougaard 2020년 10월 16일
If you wish to solve the problem using a switch/case sentence you should omit the == as that is assumed for the case. Furthermore the indexing to your cName variable should be numeric - not as characters.
This could be solved by
color=[2,1,3,0,1,3,1,0,2];
cName ={'yellow','red','green','blue'};
for ind=1:length(color)
switch color(ind)
case 0
disp(cName{1});
case 1
disp(cName{2});
case 2
disp(cName{3});
case 3
disp(cName{4});
end
end
Handling this problem in an even simpler for loop would be rather easy as well
color=[2,1,3,0,1,3,1,0,2];
cName ={'yellow','red','green','blue'};
for ind= color
disp(cName{ind+1});
end
  댓글 수: 1
Skomantas Tamulaitis
Skomantas Tamulaitis 2020년 10월 16일
That's perfect, thanks a lot!

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by