0
A = [a 2 5 8;
     b 4 8 NaN] 

其中ab1x3行向量。

我需要一个单元格数组B

B{1}=2 a
B{2}=5 a
B{3}=8 a b
B{4}=4 b

不过顺序无所谓。

所以我需要将第 4,5,6..th 列元素逐个元素地放在那些1x3行向量ab,而忽略NaN.

我的第一次尝试是unique(A),但仅此一项无法消除NaN,也无法正确匹配。

也许我还需要获取每个元素(2,5,8,4,8,)所在“行”的索引矩阵,但我找不到方法。

然后我尝试使用forand if。但是我的电脑无法处理这个巨大的文件大小。

4

1 回答 1

2

So you have a matrix A:

A = [a 2 5 8;
     b 4 8 NaN];

I'll first split the matrix into parts consisting of a and b and the rest:

a_and_b = A(:,1:3);
Arest = A(:,4:end);

then we'll see what the unique items are in this Arest matrix, and remove the NaNs:

Arest_uniq = unique(Arest);
Arest_uniq = Arest_uniq(~isnan(Arest_uniq));

check the occurences of the elements in Arest_uniq in rows of Arest:

occur_A = arrayfun(@(ii) ismember(Arest_uniq,Arest(ii,:)),1:size(A,1),'uni',false);

Because adding those rows a and/or b based on an if-construction isn't a linear operation, I'd rather just do it in a loop.

output = num2cell(Arest_uniq);
for ii=1:numel(output)
    for jj=1:size(A,1)
        if occur_A{jj}(ii)
            output{ii} = [output{ii} a_and_b(jj,:)];
        end
    end
end

Go through this with step-by-step debugging, inspect variables on the way, and eventually you'll understand what everything does. So next time you can solve your problems yourself on the spot.

于 2013-07-29T07:12:16.153 回答