如何在MATLAB中从矩阵中删除零?

时间:2014-08-27 15:16:20

标签: arrays matlab matrix vector jagged-arrays

这是我的问题:

我在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

2 个答案:

答案 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{:}