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
% 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.
댓글 수: 0
채택된 답변
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
figure;
plot(t,abs(f),'r')
xlabel('t')
grid on
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!