在有条件的巨大矩阵上计算平均值 [英] Counting average on huge matrix with conditional

查看:88
本文介绍了在有条件的巨大矩阵上计算平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下MATLAB代码永久在10 ^ 5正方形矩阵A上运行.但是,它在10 ^ 3正方形矩阵上运行几秒钟.有什么办法可以加快速度吗?

The following MATLAB code runs forever on 10^5 square matrix A. However, it runs for a few seconds on 10^3 square matrix. Is there any way to speed it up?

function [meanNV]=calcMeanNV_k(A,V,d)
%A: input matrix (n x n)
%V: eigenvectors of k-th largest eigenvalues (n x 1)
%d: degrees of each node (n x 1)
%meanNV: mean of neighbors vectors (n x 1)
m=size(A,2);
meanNV=zeros(113336);
 for i=1:m
     sumNode = 0;
     for j=1:m
        if A(i,j)==1
            sumNode=sumNode+V(j);
        end
     end
    [meanNV(i)]=sumNode/d(i); 
 end

推荐答案

简单地说,对于A中的每一行,您要确定非零的位置,并使用这些索引求和V并除以d中的相应条目.

Simply put, for each row in A, you are determining the locations that are non-zero and using these indices to sum over the corresponding locations in V and dividing by the corresponding entry in d.

首先使用 find 确定非零行和列位置,然后使用 accumarray将所有列位置按其常见行分组和应用于accumarray的函数将在您索引到V后简单地对所有索引求和.

First use find to determine the non-zero row and column locations, then group all of the column locations by their common rows using accumarray and the function to apply on accumarray would simply sum over all indices once you index into V.

类似的事情可能会起作用:

Something like this could work:

function [meanNV]=calcMeanNV_k1(A,V,d)
%A: input matrix (n x n)
%V: eigenvectors of k-th largest eigenvalues (n x 1)
%d: degrees of each node (n x 1)
%meanNV: mean of neighbors vectors (n x 1)

m=size(A,2);
[row,col] = find(A); % Find non-zero entries in A
meanNV = accumarray(row, col, [m 1], @(x) sum(V(x))) ./ d; % Compute desired result

end

这篇关于在有条件的巨大矩阵上计算平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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