How can I improve the efficiency of an equation with double summation

2 次查看(过去 30 天)
In some of my calculations, I have to perform a double-summation and my current approach seems to be very inefficient - taking several seconds to complete. The equation that I am trying to calculate is shown below (it has been simplified for clarity).
In this equation:
  • f(t) and y(t) are each [1 x 10001] vectors
  • M = 100
  • x(n) is a 101 (M+1) vector of positive numbers (type: double)
  • i is an imaginary number
I looked at a handful of loop optimization answers such as https://www.mathworks.com/matlabcentral/answers/877868-suggestions-for-vectorizing-double-triple-for-loops-in-matlab but none of the solutions that I found appeared to have more than small impact on my calculation time.
My approach
(I split it up into multiple terms within the for loops because there are a handful of scalar factors omitted here)
rng("default")
M = 100;
% Some temporary vectors so that the code can run
t = linspace(2,10,10001);
y = sqrt(t);
x = abs(randn(1,M+1));
tic
% Preallocate 3D Matrix
fsum = zeros(length(y),M+1,M+1);
% Loop through to calculate each M term
for m = 0:M
for n = 1:M+1
term1 = 1i.*y/((m+1)*x(n));
num2 = 2*m + 5*x(n);
den2 = 7;
term2 = (num2/den2 + 1i.*y).^(-1);
fsum(:,m+1,n) = term1.*term2;
end
end
% Now sum away the 2nd and 3rd dimensions
fsum = sum(fsum,[2 3]);
% Now that we have the summation term as a vector that matches y(t),
% we can insert it into the f equation
f = 1./(1 - fsum);
toc
Elapsed time is 2.938936 seconds.
% Simple plot to make sure that f became a function of t
figure;
plot(t,abs(f),'r')
xlabel('t')
grid on
Is there anything that I can do to speed up the calculation of this vector f(t)? Currently the y(t) vector is only 10,001 points but I would like to increase that in the future to address some resolution issues that I am having with subsequent calculations.

采纳的回答

Torsten
Torsten 2023-1-31
编辑:Torsten 2023-1-31
rng("default")
M = 100;
% Some temporary vectors so that the code can run
t = linspace(2,10,10001);
y = sqrt(t);
x = abs(randn(1,M+1)).';
tic
%mat = zeros(M+1);
f = zeros(size(t));
v = 0:M;
f = arrayfun(@(i)sum(1i*y(i)./((v + 1).*x)./((2*v + 5*x)/7 + 1i*y(i)),'All'),1:numel(y));
%for i=1:numel(y)
% mat = 1i*y(i)./((v + 1).*x)./((2*v + 5*x)/7 + 1i*y(i));
% f(i) = sum(mat,'All');
%end
f = 1./(1-f);
toc
Elapsed time is 0.771715 seconds.
figure;
plot(t,abs(f),'r')
xlabel('t')
grid on

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

产品


版本

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by