简体   繁体   English

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

[英]How to delete zeros from matrix in MATLAB?

Here is my problem: 这是我的问题:

I have a nxn matrix in matlab. 我在matlab中有一个nxn矩阵。 I want to delete all the zeros of this matrix and put the rows of it in vectors. 我想删除此矩阵的所有零,并将其行放在向量中。 For n=4 , let say I have the following matrix: 对于n=4 ,假设我有以下矩阵:

A = [ 1 1 0 0
      1 2 0 0
      1 0 0 0
      1 2 1 0 ];

How to get the following: 如何获得以下内容:

v1 = [ 1 1 ]; 
v2 = [ 1 2 ]; 
v3 = [ 1 ]; 
v4 = [ 1 2 1 ]; 

I did the following: 我做了以下事情:

for i = 1:size(A, 1)
    tmp = A(i, :);
    tmp(A(i, :)==0)=[];
    v{i} = tmp;
end

Slightly faster than Divakar's answer : Divakar的回答快一点:

nzv = arrayfun(@(n) nonzeros(A(n,:)), 1:size(A,1), 'uniformoutput', false);

Benchmarking 标杆

Small matrix 小矩阵

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.

Large matrix 大矩阵

A = randi([0 3],1000,2000);
repetitions = 100;

Elapsed time is 11.483947 seconds.
Elapsed time is 5.563153 seconds.

Convert to a cell array such that you have a cell for each row and then use nonzeros for each cell, that deletes zeros and finally store them into separate variables. 转换为单元格数组,以便每行都有一个单元格,然后为每个单元格使用nonzeros值,删除零并最终将它们存储到单独的变量中。

Code

nzv =cellfun(@(x) nonzeros(x),mat2cell(A,ones(1,size(A,1)),size(A,2)),'uni',0)
[v1,v2,v3,v4] = nzv{:}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM