Maddy
Maddy

Reputation: 2570

cell to matrix matching / map / cellOperations (MATLAB)

I cannot find the string equivalent of the finalAnswer using the data below. Please, I cannot use if/for loops! A final answer is preferred with each element as an array (i.e. the format of mainData)

mainData = {'IBM' [201] [1] ; 
            'GE' [403] [1] ; 
            'MSFT' [502] [3] ;
            'GM' [101] [2]       } ;

finalAns = [ 101 2 0.5; 403 1 0.6 ]                  ;

%% I tried doing this ->
temp = cell2mat(mainData(:,[2 3])) ;

tf = ismember(temp, finalAns(:,[1 2],'rows') ;
secIDs = mainData(tf) ;

Upvotes: 2

Views: 457

Answers (1)

gnovice
gnovice

Reputation: 125874

In order to get the entries in each row of mainData that match those in finalAns (based on the last two columns of mainData and the first two columns of finalAns) and to get them in the same order that they appear in finalAns and with the last column of finalAns appended, you can do this:

>> temp = cell2mat(mainData(:,2:3));
>> [isThere,index] = ismember(finalAns(:,1:2),temp,'rows');
>> output = [mainData(index(isThere),:) num2cell(finalAns(isThere,3))]

output = 

    'GM'    [101]    [2]    [0.5000]
    'GE'    [403]    [1]    [0.6000]

The output is a 2-by-4 cell array with each value in a separate cell. If you want the last three columns to be collected in a vector, you can replace the calculation of output above with this:

>> temp = [temp(index(isThere),:) finalAns(isThere,3)];
>> output = [mainData(index(isThere),1) num2cell(temp,2)]

output = 

    'GM'    [1x3 double]
    'GE'    [1x3 double]

Note that now you have a 2-by-2 cell array where cells in the second column contain 1-by-3 double arrays.

Upvotes: 2

Related Questions