向量化矩阵中不同对角线的总和 [英] Vectorizing sums of different diagonals in a matrix

查看:82
本文介绍了向量化矩阵中不同对角线的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向量化以下MATLAB代码.我认为它一定很简单,但是我仍然感到困惑.

I want to vectorize the following MATLAB code. I think it must be simple but I'm finding it confusing nevertheless.

r = some constant less than m or n
[m,n] = size(C);
S = zeros(m-r,n-r);
for i=1:m-r+1
    for j=1:n-r+1
        S(i,j) = sum(diag(C(i:i+r-1,j:j+r-1)));
    end
end

该代码从另一个得分表 C 中为动态编程算法计算得分表 S .
对角线求和是为所有可能的数据块(大小为r)生成用于生成 C 的数据的单个数据块的分数.

The code calculates a table of scores, S, for a dynamic programming algorithm, from another score table, C.
The diagonal summing is to generate scores for individual pieces of the data used to generate C, for all possible pieces (of size r).

在此先感谢您提供任何答案!抱歉,这应该很明显...

Thanks in advance for any answers! Sorry if this one should be obvious...

注意
事实证明,内置的conv2比convnfft更快,因为我的eye(r)很小(5≤r≤20). convnfft.m指出,r的值应大于20才能体现出来.

Note
The built-in conv2 turned out to be faster than convnfft, because my eye(r) is quite small ( 5 <= r <= 20 ). convnfft.m states that r should be > 20 for any benefit to manifest.

推荐答案

如果我理解正确,则您正在尝试计算C的每个子数组的对角线总和,其中删除了C的最后一行和一列(如果您不应该删除行/列,需要循环到m-r + 1,并且需要将整个数组C传递给下面我的解决方案中的函数).

If I understand correctly, you're trying to calculate the diagonal sum of every subarray of C, where you have removed the last row and column of C (if you should not remove the row/col, you need to loop to m-r+1, and you need to pass the entire array C to the function in my solution below).

您可以通过卷积进行此操作,就像这样:

You can do this operation via a convolution, like so:

S = conv2(C(1:end-1,1:end-1),eye(r),'valid');

如果C和r大,则可能需要查看 CONVNFFT 可以加快计算速度.

If C and r are large, you may want to have a look at CONVNFFT from the Matlab File Exchange to speed up calculations.

这篇关于向量化矩阵中不同对角线的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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