sparse indexing in matlab

南笙酒味 提交于 2019-12-12 02:49:54

问题


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;


来源:https://stackoverflow.com/questions/26597271/sparse-indexing-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!