Search code examples
matlabmatrixsparse-matrix

Optimize deleting matrix leading zeros in MATLAB


After profiling my code, it looks like it resides most of the time in the following loop. This code iterate over a matrix lines and delete the leading zeros of each line Any idea how to optimize it? Note that the matrix is sparse, so it might help

Thanks!

inCB = sparse(inCB); 
cbR = inCB*0; % init result CB matrix

Nwin = size(inCB,2);
for k=1:size(inCB,1)
    n = find(inCB(k,:)>0,1); % getting how many leading zeros we need to delete
    if ~isempty(n)
        cbR(k,:) = [inCB(k, n:Nwin) zeros(1, (n-1))]; %delete leading zeros (and padding the end with zeros )

    end
end

Solution

  • %code can only remove leading zeros in each column, transpose
    m=inCB';
    %create a logical matrix of the data we want
    h=cumsum(m)>0;
    %preallocate
    r=zeros(size(m));
    %remove zeros
    r(flipud(h))=m(h);
    %transpose back
    cbR=r';