Logical indexing in categorical array

I want to ask about the logical indexing at the end. This is from Mathworks website. Looking at B(TF), it doesn't seem to convey anything meaningful. What am I missing?

5 Comments

Hi Deepayan,
You aren't missing anything, this instead shows that with this example, the code is able to index the three category instances of 'red'. This can be valuable if you wanted to change these red categories to a different category, like 'green' or 'blue', or even a new category, like 'purple'. I do believe that the purpose of that example is that the equality now works over the entire array, which is a very nice feature of this category instance.
So it is really much more of a specific case of some relatively unique and convenient functionality of the categorical type in MATLAB.
Best,
Michael
Perhaps a more obviously useful example would be to show those elements of the categorical array that are not red.
rng default % So we generate the same A each time
A = randi(3, [3 3])
B = categorical(A, 1:3, ["red"; "green"; "blue"])
TF = B ~= "red"
nonred = B(TF)
When I do this, I get this error
>> B = categorical(A, 1:3, ['red'; 'green'; 'blue'])
Dimensions of matrices being concatenated are not consistent.
With " ", I get
>> B = categorical(A, 1:3, ["red"; "green"; "blue"])
B = categorical(A, 1:3, ["red"; "green"; "blue"])
Error: Creating a string using double quotes is not supported. Use the string function.
Did you mean:
>> B = categorical(A, 1:3, [string('red'); string('green'); string('blue')])
Error using categorical (line 380)
CATEGORYNAMES must be a cell array of non-empty character vectors.
You're using an older release of MATLAB. Using a cell array of char vectors rather than a string array:
rng default % So we generate the same A each time
A = randi(3, [3 3])
B = categorical(A, 1:3, {'red'; 'green'; 'blue'})
TF = B ~= 'red'
nonred = B(TF)
I got it now :)

Sign in to comment.

Answers (0)

Categories

Asked:

on 18 Aug 2020

Commented:

on 20 Aug 2020

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!