How to delete zeros from matrix in MATLAB?

∥☆過路亽.° 提交于 2019-12-01 22:11:10
Luis Mendo

Slightly faster than Divakar's answer:

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.

Code

nzv =cellfun(@(x) nonzeros(x),mat2cell(A,ones(1,size(A,1)),size(A,2)),'uni',0)
[v1,v2,v3,v4] = nzv{:}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!