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

4 views (last 30 days)
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 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)
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));
% 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;
% 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);
Elapsed time is 2.938936 seconds.
% Simple plot to make sure that f became a function of 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.

Accepted Answer

Torsten on 31 Jan 2023
Edited: Torsten on 31 Jan 2023
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)).';
%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');
f = 1./(1-f);
Elapsed time is 0.771715 seconds.
grid on
  1 Comment
Emma Farnan
Emma Farnan on 31 Jan 2023
Thank you! This is so much faster and I definitely wouldn't have thought of using arrayfun on my own

Sign in to comment.

More Answers (0)




Community Treasure Hunt

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

Start Hunting!