在 matlab 中使用逐元素加法将值添加到矩阵的对角线 [英] adding values to diagonals of matrix using element-wise addition in matlab

查看:43
本文介绍了在 matlab 中使用逐元素加法将值添加到矩阵的对角线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个对矩阵进行运算的脚本,我遇到了需要将前一个矩阵的对角线总和添加到新矩阵的对角线元素的问题.到目前为止,我为这个特定函数编写的代码(下面有更详细的描述)是:

I am writing a script that operates on matrices, and I have run into the problem of needing to add the sum of the diagonals of a previous matrix to the diagonal elements of a new matrix. The code I have so far for this particular function (described in more detail below) is:

t = 1;
for k = (m-1):-1:-(m-1)
    C = bsxfun(@plus, diag(B, k), d);
    g(t) = sum(diag(B, k));
    t = t + 1;
end

其中 d 是一个 1x3 数组,而 C 应该是一个 3x3 数组;然而,C 以 1x3 数组的形式输出,这样第一个对角线被求和并添加到 d,然后主对角线被求和并添加到 d,最后的对角线被求和并添加到 d.

where d is a 1x3 array, and C is supposed to be a 3x3 array; however, C is being output as a 1x3 array in such a way that the first diagonal is being summed and added to d, then the main diagonal is being summed and added to d, and the final diagonal is being summed and added to d.

有没有办法让 C 的值达到这样的程度,即第一个对角线是添加到 d 的最后一个元素的单个元素的总和,添加到 d 的中间元素的主对角线的单个元素的总和,以及底部对角线的元素添加到 d 的第一个元素?(同时仍然适用于任何数组大小?)

Is there a way I can get the values of C to be such that the first diagonal is the sum of it's individual elements added to the last element of d, the main diagonal's individual elements added to the middle element of d, and the bottom diagonal's elements added to the first element of d? (while still working for any array size?)

这是一张描述我想要实现的目标的图片:

Here is a picture that describes what I'm trying to achieve:

谢谢!

推荐答案

您可以使用 toeplitz 生成一个矩阵,其中包含需要添加到原始矩阵的值:

You can use toeplitz to generate a matrix containing the values that need to be added to your original matrix:

M = [5 5 5; 7 7 7; 9 9 9]; %// data matrix
v = [1 11 4 3 2]; %// data vector
S = toeplitz(v);
S = S(1:(numel(v)+1)/2, (numel(v)+1)/2:end);
result = M+S;

或者,如@thewaywewalk 所述,您可以更直接地执行此操作,如下所示:

Or, as noted by @thewaywewalk, you can do this more directly as follows:

M = [5 5 5; 7 7 7; 9 9 9]; %// data matrix
v = [1 11 4 3 2]; %// data vector
result = M + toeplitz(v(size(M,1):-1:1), v(size(M,2):end));

这篇关于在 matlab 中使用逐元素加法将值添加到矩阵的对角线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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