0

In octave, I have a cell

a={{1,'abc',3.5}, {2,'abc',4.5},{3,'def',5.4}}

I want to do logical indexing similar to doing it as matrix

Something like

a(:,3} =='abc' 

should produce an array of

[1, 1, 0]

Basically, I want to produce a new cell array that only has points that have 'abc', so it should reduce to

b=a={{1,'abc',3.5}, {2,'abc',4.5}}

How can I do this?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
user2015487
  • 2,075
  • 3
  • 17
  • 20

1 Answers1

0
a={{1,'abc',3.5}, {2,'abc',4.5},{3,'def',5.4}}
arg = 'abc'

res = cellfun(@(x) ismember(1, strcmp(x, arg)), a)

cellfun applies given function to every element of an cell array: http://www.mathworks.com/help/matlab/ref/cellfun.html

as pointed in the first link '@(x) creates an anonymous function'

this post shows how to find if a string is in cell array of mixed type: Find string in cell array with elements of different types

in this case one element of the given cell array is a cell array itself so that is what x will hold.

x is {1,'abc',3.5} -> strcmp(x, arg) is {0, 1, 0} -> ismember(1, {0, 1, 0}) evaluates to 1

x is {2,'abc',4.5} -> strcmp(x, arg) is {0, 1, 0} -> ismember(1, {0, 1, 0}) evaluates to 1

x is {3,'def',5.4} -> strcmp(x, arg) is {0, 0, 0} -> ismember(1, {0, 0, 0}) evaluates to 0

so res contains {1, 1, 0}

Community
  • 1
  • 1
eiPi10
  • 81
  • 2
  • 7