Matthias Pospiech
Matthias Pospiech

Reputation: 3494

Matlab: Select items from vector

I have a vector or a matrix where I want to select rows. The vector could look like this

T{1} = 'A'
T{2} = 'B'
T{3} = 'A'

and I want to reduce it from ABA to AA using

T([ 1 0 1])

but that does not compile, if I do

T([ 1 2 3]) 

I get the original. However I select the rows using a strfind function like this

indexlistM = cell2mat(strfind(T, 'A')) = [1 0 1];

How can I select rows using a true/false selector or using a different method?

Upvotes: 0

Views: 68

Answers (2)

Matthias Pospiech
Matthias Pospiech

Reputation: 3494

The idea how to provide a logical array or an index is already answered. Here I want to demonstrate the solution with code examples:

contains(T, 'A')
ans =
  1×3 logical array
   1   0   1

or using an index with find

find(contains(T, 'A'))
ans =
 1     3

In both cases the result is

  1×2 cell array
    {'A'}    {'A'}

Upvotes: 0

Wolfie
Wolfie

Reputation: 30047

The error you got for running this

T([1 0 1])

is quite descriptive

Subscript indices must either be real positive integers or logicals.

You have provided a non-positive integer (0) which isn't a logical (false).

You can either do

T( [true false true] ); % = T( logical([1 0 1]) )

MATLAB sometimes obfuscates the type for logical arrays (which can make this confusing) because it's easier to display and read logicals in numeric format, but to use logical indexing you need the array to be an actual logical type, not a double

[true false true]
ans =
  1×3 logical array
   1   0   1

Or use the index

T( [1 3] )

Upvotes: 1

Related Questions