Matlab中的稀疏索引 [英] sparse indexing in matlab

查看:149
本文介绍了Matlab中的稀疏索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很长的代码,里面充满了以下"if",而matlab编辑器给了我如下建议:

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

这种稀疏索引表达可能很慢

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;

有什么方法可以使代码更快,并满足matlab的建议? (该代码可能无法运行,因为我只是选择了几行并试图显示该问题)

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)

推荐答案

嵌套的forif等效于以下矢量化代码:

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;

这篇关于Matlab中的稀疏索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆