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:');
disp(Psnj_optimized);
I hope this will help!