Search code examples
matlabcellmatching

Searching for a matched string within nested cell and delivering the index


I have a nested cell array which is called values. Description as an image. In this example, there are 5 sub cells. Usually this number is variable from 1 to 30. Each cell has two subsub cells:

  1. he first one, or values{5,1}{1,1}, has always only one char value (in this example, TOTAL or MGS)
  2. the second one, or values{5,1}{2,1}, has matrix consisting from tow columns: on the left - tempearature values, on the right - physical properties.

My goal is to find the sub cell containing the char value 'TOTAL' (values{5,1}) and somehow to get the index of the matrix (the output would be values{5,1}{2,1})

To adress the challenge, I have written my handmade solution. This code works if there is in the char 'TOTAL' in a{5,1}{1,1} and takes a corresponding value next to 298.15 K. However, the string 'TOTAL' could be elsewhere. In this case, I have a problem. In this solution, the double loop takes long time. So, do you have another solution how to find the index of a cell with 'TOTAL' avoiding loops?

    for m = 1:numel(values)
        for n = 1:numel(values(m))
            a = values(m);
            if string(a{5,1}{1,1}) == 'TOTAL'
                k = a{5,1}{2,1}(:,1); %column with temp numbers
                n = 298.15;           %RT
                [~,~,idx] = unique(round(abs(k-n)));
                minVal = k(idx==1);
                valueAtRT = sprintf('%f', a{1,1}{5,1}(length(a{1,1}{5,1})+idx));
                break;
            end
        end
    end

Thanks for any help.


Solution

  • I have found the solution assuming there is only one cell with 'TOTAL':

    is = cellfun( @(cac) strcmp(cac{1},'TOTAL'), values, 'uniformoutput',false  );
    num = values{is}{2};
    valueAtRT = interp1( num(:,1), num(:,2), 298.15, 'nearest', 'extrap' );
    

    is delivers the index of the cell, where the char 'TOTAL' is stored and the third line delivers the value next to 298.15.