sparse indexing in matlab

2019-09-15 17:03发布

问题:

I have a very long code which is full of the following "if"s and matlab editor gives me a suggestion as follow:

this sparse indexing expression is likely to be slow

mt = rand(200,200);
[c r] = size(mt);
T = sparse(r*c,2);

for i = 1:c 
    for j = 1:r 
        if(ind(j,i)==1)
            templat = template + 1;
            T((i-1)*r+j,2)=100000;
        end
    end;
end;

Is there any way by which I can make the code faster and do the matlab's suggestion? (The code may not run, because I just picked a few lines and tried to show the issue)

回答1:

The nested for's and if are equivalent to the following vectorized code:

[jj, ii] = find(ind==1); %// jj is rows, ii is columns
templat = template + numel(ii);
T((ii-1)*r+jj,2) = 10000;