这是我的问题:
我在matlab中有一个nxn
矩阵。我想删除此矩阵的所有零,并将其行放在向量中。对于n=4
,假设我有以下矩阵:
A = [ 1 1 0 0
1 2 0 0
1 0 0 0
1 2 1 0 ];
如何获得以下内容:
v1 = [ 1 1 ];
v2 = [ 1 2 ];
v3 = [ 1 ];
v4 = [ 1 2 1 ];
我做了以下事情:
for i = 1:size(A, 1)
tmp = A(i, :);
tmp(A(i, :)==0)=[];
v{i} = tmp;
end
答案 0 :(得分:3)
略快于Divakar's answer:
nzv = arrayfun(@(n) nonzeros(A(n,:)), 1:size(A,1), 'uniformoutput', false);
A = randi([0 3],100,200);
repetitions = 1000;
tic
for count = 1:repetitions
nzv =cellfun(@(x) nonzeros(x),mat2cell(A,ones(1,size(A,1)),size(A,2)),'uni',0);
end
toc
tic
for count = 1:repetitions
nzv = arrayfun(@(n) nonzeros(A(n,:)), 1:size(A,1), 'uniformoutput', false);
end
toc
Elapsed time is 3.017757 seconds.
Elapsed time is 2.025967 seconds.
A = randi([0 3],1000,2000);
repetitions = 100;
Elapsed time is 11.483947 seconds.
Elapsed time is 5.563153 seconds.
答案 1 :(得分:2)
转换为单元格数组,以便每行都有一个单元格,然后对每个单元格使用nonzeros
,删除零并最终将它们存储到单独的变量中。
<强>代码强>
nzv =cellfun(@(x) nonzeros(x),mat2cell(A,ones(1,size(A,1)),size(A,2)),'uni',0)
[v1,v2,v3,v4] = nzv{:}