Switch case on an array
Mostrar comentarios más antiguos
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 comentarios
Geoff Hayes
el 19 de Sept. de 2019
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
el 19 de Sept. de 2019
Guillaume
el 19 de Sept. de 2019
<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.
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Matrix Indexing en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!