How to avoid nested for loop to make the code faster?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Stef
am 14 Mär. 2019
Beantwortet: Doug Mercer
am 14 Mär. 2019
Hi everyone!
Do you have some suggestions to improve the following code?
As it is now, it is very slow…
B_2 = zeros(d,d);
for m = 1:M
for n = m+1 : 2*N
B_2 = B_2 + 4*N^(-1)* A(n) * B(n-m);
end
end
where A(n) and B(n) are 2x2 real, symmetric and full rank, matrices for all possible value of n.
Thanks in advance!
6 Kommentare
Akzeptierte Antwort
Doug Mercer
am 14 Mär. 2019
If you can generate A and B in a vectorized manner (i.e., for inputs x=[x_1, x_2, ..., x_k] the function A(x) returns a 2x2xk 3D array where a(:, :, i) is the 2x2 array corresponding to x_i) then the following would vectorize the inner loop.
function B_2 = stef()
d = 2;
N = 10^5;
M = sqrt(N);
B_2 = zeros(d,d);
for m = 1:M
n_iter = m+1:2*N;
B_2 = B_2 + 4*N^(-1)*sum(A(n_iter).*B(n_iter - m), 3);
end
function b = B(x)
b = rand(2, 2, length(x));
function a = A(x)
a = rand(2, 2, length(x));
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!