Switch case on an array
77 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
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 Loops and Conditional Statements 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!