Logical indexing in categorical array
Show older comments
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
Michael Soskind
on 19 Aug 2020
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
Steven Lord
on 19 Aug 2020
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)
Deepayan Bhadra
on 19 Aug 2020
Edited: Deepayan Bhadra
on 19 Aug 2020
Steven Lord
on 20 Aug 2020
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)
Deepayan Bhadra
on 20 Aug 2020
Answers (0)
Categories
Find more on Categorical Arrays 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!