Switch case on an array
77 views (last 30 days)
Given the following code
TA = 0
TB = 0
TC = 0
x = [12 64 24];
s = num2str(x);
n = length(s)
TA = TA + 1;
TB = TB + 1;
TC = TC + 1;
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?
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:
x = [12 24 64 24 12 12]
lookup = [12, 24, 64]; %values to compute the histogram of
count = zeros(size(lookup))
for i = 1:numel(x)
[found, where] = ismember(x(i), lookup);
count(where) = count(where) + 1;
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