How to remove zeros from a matrix in MATLAB?

Here's my problem:

I have a matrix nxn

in matlab. I want to remove all zeros from this matrix and put its rows in vectors. For n=4

let's say I have the following matrix:

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

      

+3


source to share


2 answers


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.

      

+3


source


Convert to a cell array so you have a cell for each row and then use nonzeros

for each cell that removes the zeros and finally stores them in 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{:}

      

+2


source







All Articles