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!