迭代地扩展单元格数组

时间:2016-09-08 12:15:12

标签: arrays matlab cell

我有两个不同大小的单元格数组,想要将cellarray1第一列中的单元格与第一列cellarray2的单元格进行比较。如果两个单元格相等,请获取cellarray2中该行的后续列中的信息[可以是字符串,为int],并将其放在cellarray1中。我真正需要的是知道如何灵活扩展cellarray1

两个数组的第一列是字符串,Po001, Po002等...... Cellarray1将包含每个字符串的两个副本,Po001, Po001, Po002, Po002等 就是这样,我需要匹配两个数组,如果它们匹配,我在cellarray2的其他列中添加信息,这应该是通用的, 也就是说,第二列包含具有两个值的字符串,例如Object1, Object2。第三列包含12。只是我不知道如何使用新单元格扩展cellarray行,在整个for循环后,在cellarray1中生成N个新列。

for ii = 1:length(cellarray2(:,1))
     for jj = 1:length(cellarray1(:,1))
         if strcmp(cellarray2{ii,1}, cellarray1{jj,1})
            % This seems to give the results I want but I 
            % dont know how to update the original cellarray1 
            % with this new row 
            [cellarray1(ii,1:end), cellarray2(jj,1:end)]
         end
     end
end

如果可以做到这一点真的很好。理想情况下,我想在cellarray2的第一列之后输入来自cellarray1的信息。就像在cellarray1中为cellarray2的每一列创建一列,然后在cellarray1中输入该信息,如果比较是true的话。

最好的问候,
花岗岩

2 个答案:

答案 0 :(得分:2)

您可以使用cellarray1(:,1)cellarray2(:,1)cellfun

创建索引向量,以指示find中哪些行与strcmp匹配
% Find the first location of match from cellarray1 in cellarray2
locIdx = cellfun(@(x)find(strcmp(x,cellarray2(:,1)),1),cellarray1(:,1)); 

现在,您可以将cellarray2cellarray1的列复制为:

cellarray1(:,2:end) = cellarray2(locIdx,2:end);  
% I used 2:end assuming you want to copy only the non key columns

或者,如果您想将列附加到cellarray1

width2 = size(cellarray2,2);
cellarray1(:,end+1:end+width2-1) = cellarray2(locIdx,2:end);

答案 1 :(得分:0)

来自@Some Guy的答案会使用cellarray2中的值覆盖cellarray1中的值。我觉得你正在寻找一个解决方案,你可以在阵列的末尾添加它们,所以如果我在这里就是一个解决方案:

%please always add data examples to your posts
cellarray1={'A' 1;'B' 2;'C' 3;'D' 4;'E' 5};
cellarray2={'A' 'X'; 'D' 'Y';'E' 'Z'};

%there is no width() so you have to do it like this or with size()
width1=length(cellarray1(1,:));
width2=length(cellarray2(1,:));

for ii = 1:length(cellarray2(:,1))
     for jj = 1:length(cellarray1(:,1))
         %you got the ii and jj mixed up here
         if strcmp(cellarray2{ii,1}, cellarray1{jj,1})
           %either you overwrite everything with this 
           %cellarray1(ii,1:width1+width2-1) = [cellarray1(ii,:) cellarray2(jj,2:end)];
           %or you just add them at the end on cellarray1 with this
           cellarray1(jj,width1+1:width1+width2-1) = cellarray2(ii,2:end);
         end
     end
end

请注意,当if情况首次为真时,cellarray1会将其大小从(X,width1)更改为(X,width1 + width2-1)。 另外我觉得性能在这里不是问题,但是如果这个cellarray1和cellarray2真的很大或者这个函数应该被调用很多,你应该为两个循环进行矢量化。

相关问题