Home > Net >  Matlab: Select items from vector
Matlab: Select items from vector

Time:10-27

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?

CodePudding user response:

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] )

CodePudding user response:

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'}
  • Related