Bro2ma
Bro2ma

Reputation: 13

MatLab find column number of text cell array

I have a cell data type matrix containing a header and a large number of rows.

sample data:

set         press       dp
32.7045     17.805965   123.75047
32.690094   17.80584    123.74992
32.6232     17.815094   123.790115

I am trying to find the index of a specific column using the strcmp command to search through the all the data.

dpCol = strcmp([data{:}], 'dp')

This always returns

dpCol =

     0

Am I using the data cell type wrong or something? Thank you!

Upvotes: 1

Views: 200

Answers (1)

Mark Mikofski
Mark Mikofski

Reputation: 20198

Try using cell notation to yield just the 1st row, EG:

data(1,:) = {'set','press','dp'}

instead of unpacking* the entire cell array since strcmp can operate on cell arrays.

>>> data = {'set'         'press'       'dp'
32.7045     17.805965   123.75047
32.690094   17.80584    123.74992
32.6232     17.815094   123.790115}

data = 

    'set'        'press'      'dp'      
    [32.7045]    [17.8060]    [123.7505]
    [32.6901]    [17.8058]    [123.7499]
    [32.6232]    [17.8151]    [123.7901]

>>> col_idx = strcmp(data(1,:),'dp')

col_idx=

     0     0     1

Then return the dp using the logical indices and cell2mat...

>>> dp = cell2mat(data(2:end,col_idx))
dp =

  123.7505
  123.7499
  123.7901

or unpack* and concatenate the comma separated list

>>> dp = [data{2:end,col_idx}]

dp =

  123.7505  123.7499  123.7901

As an alternative try cell2struct.

>>> datastruct = cell2struct(data(2:end,:),data(1,:),2)
datastruct = 

3x1 struct array with fields:

    set
    press
    dp

Then dp is ...

>>> dp = [datastruct.dp]

dp =

  123.7505  123.7499  123.7901

* Using the colon operator inside curly braces unpacks an cell array into a comma separated list. Using square brackets horizontally concatenates the comma separated list which returns a character array set pressdp{{{ since the first item in the list is a character array. The garbage characters between and after 'set', 'press' and 'dp' are caused by reading the doubles as char. IE: char(32.7045) is the ASCII equivalent of whitespace. The arrays always get unpacked as column.

Upvotes: 2

Related Questions