Avoiding doble loops to gain efficience

9 visualizzazioni (ultimi 30 giorni)
Javier
Javier il 13 Gen 2014
Risposto: Arjun il 28 Ott 2024 alle 12:07
Hi.
I have solved a problem by using a doble loop but it is taking too long and I am pretty sure there are more efficient ways to solve it, but I am quite a begginer with the program. I would be glad if you could help me with this.
Basically, I have two arrays of different size and I want to multiply each element of the first array for all the elements of the second one. The second vector also changes size in every iteration and that's why I have ended with a doble loop. I am doing something like this.
for j=1:length(s)
t=T-s(j):0.00025:T-0.00025;
for i=1:length(x)
aux1=exp(-x(i)^2/2./(T-t))./((t.*(T-t)).^(3/2));
aux2=sum(aux1)*0.00025;
omega(i)=exp(-mu^2/2*T+mu.*x(i)).*x(i)/2/pi.*aux2;
end
aux3=sum(omega)*0.00025;
Psnj(j)=aux3*exp(-lambda*s(j));
end
How could I do this more efficiently?
Thank you in advance Javier

Risposte (1)

Arjun
Arjun il 28 Ott 2024 alle 12:07
I see that you have solved a problem using double loop, but you are looking for more efficient ways to do this.
You can achieve this by utilizing MATLAB's vectorization capabilities. Instead of iterating over each element of "x" within a loop, you can vectorize the inner loop. Additionally, perform pre-computation to calculate any constant values outside the loop, ensuring that these operations aren't repeated with each loop execution.
Kindly refer to the code below for better understanding of the implementation:
% Assume some sample data for testing the code
T = 1.0;
mu = 0.5;
lambda = 0.1;
s = linspace(0.1, 0.5, 5);
x = linspace(0.1, 1.0, 10);
% Initialize result array at beginning to avoid resizing
Psnj_original = zeros(1, length(s));
% Precompute constants to avoid duplicate computation
dt = 0.00025;
constantFactor = exp(-mu^2/2*T) / (2*pi);
for j = 1:length(s)
t = T - s(j):dt:T - dt;
commonTerm1 = 1 ./ ((t .* (T - t)).^(3/2));
% Vectorized calculation of aux1 for all x
aux1 = exp(-x'.^2 / 2 ./ (T - t)) .* commonTerm1;
aux2 = sum(aux1, 2) * dt;
% Calculate omega using vectorization
omega = constantFactor * exp(mu .* x) .* x .* aux2';
% Sum omega and calculate Psnj
aux3 = sum(omega) * dt;
Psnj_optimized(j) = aux3 * exp(-lambda * s(j));
end
disp('Optimized Approach Results:');
Optimized Approach Results:
disp(Psnj_optimized);
1.0e-03 * 0.2152 0.3539 0.4742 0.5865 0.6990
I hope this will help!

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by