Switch case on an array
이전 댓글 표시
Given the following code
TA = 0
TB = 0
TC = 0
x = [12 64 24];
s = num2str(x);
n = length(s)
for k=1:n
switch s(k)
case 12
TA = TA + 1;
case 24
TB = TB + 1;
case 64
TC = TC + 1;
end
end
I would like to create a switch case depending on the value on x.
Following the code, the final result should be
TA = 1
TB = 1
TC = 1
But I don't know how to write x in the right character array, and the code give me a wrong result.
Which is the most clever way to solve this problem?
댓글 수: 4
Geoff Hayes
2019년 9월 19일
Luca - part of the problem is that s is an array of strings, so if you are determined to use a switch statement, then you will need to loop over each element in that array so that each element is considered. Then, since each element in the array is a string, you need to realize that your cases are assuming numbers. Perhaps there is no need to convert each number to a string?
luca
2019년 9월 19일
Guillaume
2019년 9월 19일
<pedantic> s is a char array not an array of strings which is a different thing since R2016b. </pedantic>
It's difficult to answer the question without an explanation of why s is char array instead of the more useful numeric vector x. We need an explanation of what the whole purpose of the code is.
As it is the code presented looks very badly designed, with unnecessary number to string conversions and sequentially named variables.
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!