Search code examples
matlabcell

Selecting all columns in a cell array that contain a certain value in the first row?


I currently have a 4x3500 cell array. First row is a single number, 2 row is a single string, 3rd and 4th rows are also single numbers.

Ex:

1    1    2   3   3   4   5   5   5   6
hi   no   ya  he ........ % you get the idea
28   34   18  0   3 ......
55   2    4   42  24 .....

I would like to be able to select all columns that have a certain value in the first row. ie if I wanted '1' as the first row value, it would return

1    1
hi   no
28   34
55   2

Then I would like to sort based on the 2nd row's string. ie if I wanted to have'hi', it would return:

1
hi
28
55

I have attempted to do:

variable = cellArray{:,find(cellArray{1,:} == 1)}

However I keep getting:

Error using find
Too many input arguments.

or

Error using ==
Too many input arguments.

Any help would be much appreciated! :)


Solution

  • {} indexing will return a comma separated list which will provide multiple outputs. When you pass this to find, it's the same as passing each element of your cell array as a separate input. This is what leads to the error about to many input arguments.

    You will want to surround the comma-separated list with [] to create an array or numbers. Also, you don't need find because you can just use logical indexing to grab the columns you want. Additionally, you will want to index using () to grab the relevant rows, again to avoid the comma-separated list.

    variable = cellArray(:, [cellArray{1,:}] == 1)