Search code examples
matlabcell-array

Merging to dataset together according to key


I have two datasets stored in a cell array and a double array, respectively. The design of the two arrays is:

Array 1 (name: res) (double) is composed of two columns; a unique id column and a data column.

enter image description here

Array 2 (name: config) (cell array) contains 3 column cells, each with a string inside. The last cell in the array contains a id double integer matching the id's in Array 1. The double integer in the cell array is converted to a double when necessary.

enter image description here

I want to merge the two datasets in order to have the 3 cells in the cell array AND the result column in Array 1 in one common cell array. How do I do this?

I have the following code. The code does not return the correct order of the results.

function resMat = buildResultMatrix(res, config)

resMat = {};

count = 1;

count_max = size(res,1)/130;

for i = 1 : size(res,1)
   for j = 1 : size(res,1)
       if isequal(res(i),str2double(config{j,3}))
           if i == 1
               resMat(end+1,:) = {config{j,:} res(j,2:end)};
           else
               if count == 1
                   resMat(end+1,:) = {config{j,:} res(j,2:end)};
               elseif count == count_max
                   resMat(end+1,:) = {config{j,:} res(j,2:end)};
               else
                   resMat(end+1,:) = {config{j,:} res(j,2:end)};
               end
               count = count + 1;
            end
        end
    end
    count = 1;
end
end

Solution

  • First convert the id in config to numbers:

    config(:,3) = num2cell(str2double(config(:,3)));
    

    Then run this:

    res = sortrows(res,1);
    config(:,4) = num2cell(res(cell2mat(config(:,3)),2))
    

    this will put the data from res in the 4th column in config in the row with the same id.