Switch case on an array
59 views (last 30 days)
Show older comments
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 Comments
Guillaume
on 19 Sep 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.
Accepted Answer
Guillaume
on 19 Sep 2019
Yes, it's a lot clearer. So, the transition to a char array is a complete red herring. It's totally unnecessary.
Using sequentially named variables is a bad idea. It will force you to write complicated code. If you have 10 different numbers that you want to count would you add another 7 cases to your switch? How about 100 numbers, 10000 numbers. Will you write all these cases?
The answer is to use array indexing, T(1) the count of your first, T(2) the count of your 2nd number, etc. Then you can use a loop. For example,one (inneficient) way to then implement your code would be:
%input
x = [12 24 64 24 12 12]
lookup = [12, 24, 64]; %values to compute the histogram of
%code
count = zeros(size(lookup))
for i = 1:numel(x)
[found, where] = ismember(x(i), lookup);
if found
count(where) = count(where) + 1;
end
end
But the whole thing can be achieve without loops, if or case. You want to compute an histogram, use the histcounts function:
x = [12 24 64 12 12];
values = unique(x)'; %get unique values of
count = histcounts(x, [values; Inf])'; %inf is right edge of last bin
table(values, count) %for pretty display
returns
ans =
3×2 table
values count
______ _____
12 3
24 1
64 1
2 Comments
More Answers (0)
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!