向量化矩阵中不同对角线的总和

编程入门 行业动态 更新时间:2024-10-27 22:20:02
本文介绍了向量化矩阵中不同对角线的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想向量化以下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.

更多推荐

向量化矩阵中不同对角线的总和

本文发布于:2023-11-30 10:19:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649631.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对角线   矩阵   总和

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!