Remove zeros in a matrix and reduce size

Viewed 159

How to remove the zeros in a matrix and reduce its size.

This is my matrix now: enter image description here

I want it to be like this:

745,4.8
740,3
747,11
742,13
746,7.2
741,12.2

Matlab matrix: https://drive.google.com/file/d/1P5h6lhs0O2fxFcxHabAO4hU84UqAZD1m/view?usp=sharing

Can some one give me some tips/pointers on how to do it?

load('matlab_matrix.mat')
L=length(num);
num2=num(4:72,:);
L2=length(num2);
L3=length(num2(1,:));

for i=1:L2;
    for j=1:L3;
        if isnan(num2(i,j)) ~= 1;
            A(i,j)=num2(i,j);
        end     
    end    
end
2 Answers

Let's define your data:

x = [751 0 0 0
     750 0 0 0
     749 0 0 0
     748 0 0 0
     747 0 11 0
     746 0 0 7.2
     745 4.8 0 0
     744 0 0 0
     743 0 0 0
     742 0 13 0
     741 0 0 12.2
     740 3 0 0
     739 0 0 0];

Then:

ind = find(x(:,2:end));
result = [x(mod(ind-1,size(x,1))+1) x(ind+size(x,1))];

This works even if each row has a different number of nonzeros.

To understand how it works, you may want to take a look at Linear indexing.

It appears that there are unequal number of zeros in each row so just removing zeros doesn't solve the problem. You can use sparse matrix to reduce the size:

result = sparse(num);

If the matrix contains NaNs you can use:

num(isnan(num))=0;
result = sparse(num);
Related