Search code examples
matlabfindcell

MATLAB Find row in cellular array containing two variables


I am trying to find the row in the cell array that contains (for example) the value 6 and string Steel (see matrix C at bottom of question). I understand I can use the following:

>> find(strcmp(C, 'Steel'))

ans =

    11
    14
    17

Which gives me the general index, if I subtract 9 (length of matrix) I get rows 2, 5, 8. Great. And to find the value 6:

>> find([C{:}] == 6)

ans =

     1     2     3

Super. Any idea how I go about combing this information to find the 2nd row? I would like to extract the value C{2,3} essentially. I am given the value (6) and the material (Steel), and from above I know to look in the second row; but how can I pass this automatically?

C = {6, 'Concrete',  0.37,   0.33;
     6, 'Steel',     0.1,    0.1;
     6, 'Lead',      0.057,  0.057;
     10, 'Concrete', 0.41,   0.37;
     10, 'Steel',    0.11,   0.11;
     10, 'Lead',     0.057,  0.057;
     15, 'Concrete', 0.44,   0.41;
     15, 'Steel',    0.11,   0.11;
     15, 'Lead',     0.057,  0.057};

Solution

  • First, I'll find the indexes with 6 at the first column:

    index1 = find(cell2mat(cellfun(@(x) isequal(x, 6), C(:,1), 'UniformOutput', 0)));
    

    Now, the indexes with 'Steel' at the second column:

    index2 = find(cell2mat(cellfun(@(x) strcmp(x,'Steel'), C(:,2), 'UniformOutput', 0)));
    

    Finally, their intersection:

    index = intersect(index1, index2);
    

    So C(index, :) is the line you want.

    Note that if more lines would satisfy these two conditions, index would be a vector, and C(index, :) would be an n x 4 cell array.