在MATLAB中优化删除矩阵前导零

时间:2013-12-25 18:39:25

标签: matlab matrix sparse-matrix

在对我的代码进行分析之后,看起来它大部分时间都在以下循环中。 此代码迭代矩阵行并删除每行的前导零 知道如何优化它吗? 请注意,矩阵是稀疏的,所以它可能有帮助

谢谢!

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

1 个答案:

答案 0 :(得分:1)

%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';