在MATLAB中检查数组中的成员资格而没有for循环 [英] Checking membership in an array without for loop in matlab

查看:67
本文介绍了在MATLAB中检查数组中的成员资格而没有for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想简化此代码,使其不使用for循环.

I want to simplify this code to working without for loop.

for i=1:N
    for j=1:N
        if ismember(j,A)

           PID(i,i)=TFP(i,j)+ PID(i,i);

        end
    end
end

,其中 A 是包含一些标签的矩阵.我以前以N * N稀疏double的形式存储了 TFP .因此,我想出了以下解决方案,但在其中找不到实现成员资格条件(由?指定)的方法.

in which A is a matrix that contains some labels. I previously stored TFP in the form of N*N sparse double. So, I came up with the following solution but I couldn't find a way to implement membership condition (Specified by ?) in that.

PID = sum(TFP).*(?);

它可以没有循环地实现吗?

Can it be implemented without a loop?

推荐答案

您的 ismember(j,A)等同于仅使用 A 的值进行索引.因此,您可以使用它并完全避免使用 ismember 函数(这是迄今为止代码中最慢的部分).

Your ismember(j,A) is equivalent of just using the values of A to index. So you can use that and completely avoid the ismember function (which is by far the slowest part of the code).

所以优化的第一步是

A2=unique(A); % just in case you do not do this already
for i=1:N
    for j=A2
        PID(i,i)=TFP(i,j)+ PID(i,i);
    end
end

这应该已经非常快了.循环在MATLAB中还不错,并且JIT编译器对其进行了充分的优化.

This should be already very fast. Loops are not bad in MATLAB and get heavily optimized by the JIT compiler.

优化的下一步是将所有索引放在一起并删除辅助循环.您可以使用线性索引来做到这一点,所以

The next step to optimization is to get all the indices together and remove the secondary loop. You can do this with linear indexing, so

A2=unique(A); % just in case you do not do this already
for i=1:N
    PID(i,i)=sum(TFP(i,A2));
end

最后,您可以通过对角线化所需列的总和来摆脱这种情况:

And finally, you can get rid of this by diagonalizing the sum of the desired columns:

A2=unique(A); % just in case you do not do this already
PID=diag(sum(TFP(:,A2),2));

这篇关于在MATLAB中检查数组中的成员资格而没有for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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