简体   繁体   English

在 Matlab 中计算矩阵幂(矩阵多项式)的加权求和

[英]Compute weighted summation of matrix power (matrix polynomial) in Matlab

Given an nxn matrix A_k and a nx1 vector x, is there any smart way to compute给定一个 nxn 矩阵 A_k 和一个 nx1 向量 x,有没有什么聪明的方法来计算

在此处输入图片说明

using Matlab?使用MATLAB? x_i are the elements of the vector x, therefore J is a sum of matrices. x_i 是向量 x 的元素,因此 J 是矩阵的总和。 So far I have used a for loop, but I was wondering if there was a smarter way.到目前为止,我已经使用了 for 循环,但我想知道是否有更聪明的方法。

Short answer : you can use the builtin matlab function polyvalm for matrix polynomial evaluation as follows:简短回答:您可以使用内置的 matlab 函数polyvalm进行矩阵多项式评估,如下所示:

x = x(end:-1:1); % flip the order of the elements
x(end+1) = 0; % append 0
J = polyvalm(x, A);

Long answer : Matlab uses a loop internally.长答案:Matlab 在内部使用循环。 So, you didn't gain that much or you perform even worse if you optimise your own implementation (see my calcJ_loopOptimised function):因此,如果您优化自己的实现,您并没有获得那么多,或者您的表现甚至更糟(请参阅我的calcJ_loopOptimised函数):

% construct random input
n = 100;
A = rand(n);
x = rand(n, 1);

% calculate the result using different methods
Jbuiltin = calcJ_builtin(A, x);
Jloop = calcJ_loop(A, x);
JloopOptimised = calcJ_loopOptimised(A, x);

% check if the functions are mathematically equivalent (should be in the order of `eps`)
relativeError1 = max(max(abs(Jbuiltin - Jloop)))/max(max(Jbuiltin))
relativeError2 = max(max(abs(Jloop - JloopOptimised)))/max(max(Jloop))

% measure the execution time
t_loopOptimised = timeit(@() calcJ_loopOptimised(A, x))
t_builtin = timeit(@() calcJ_builtin(A, x))
t_loop = timeit(@() calcJ_loop(A, x))

% check if builtin function is faster
builtinFaster = t_builtin < t_loopOptimised

% calculate J using Matlab builtin function
function J = calcJ_builtin(A, x)
  x = x(end:-1:1);
  x(end+1) = 0;
  J = polyvalm(x, A);
end

% naive loop implementation
function J = calcJ_loop(A, x)
  n = size(A, 1);
  J = zeros(n,n);
  for i=1:n
    J = J + A^i * x(i);
  end
end

% optimised loop implementation (cache result of matrix power)
function J = calcJ_loopOptimised(A, x)
  n = size(A, 1);
  J = zeros(n,n);
  A_ = eye(n);
  for i=1:n
    A_ = A_*A;
    J = J + A_ * x(i);
  end
end

For n=100 , I get the following:对于n=100 ,我得到以下信息:

t_loopOptimised = 0.0077
t_builtin       = 0.0084
t_loop          = 0.0295

For n=5 , I get the following:对于n=5 ,我得到以下信息:

t_loopOptimised = 7.4425e-06
t_builtin       = 4.7399e-05
t_loop          = 1.0496e-04 

Note that my timings fluctuates somewhat between different runs, but the optimised loop is almost always faster (up to 6x for small n ) than the builtin function.请注意,我的时间在不同的运行之间有些波动,但优化的循环几乎总是比内置函数更快(对于小n高达 6 倍)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM