How to avoid nested for loops in Matlab for better cpu time -
i should calculate formula large value of p, 4 nested loops made code slow , inapplicable. thankful if can me better implementation use of sum , other suitable matlab commands! k(i,j)=sum(sum(a(m)*b(n)*a(i,j,m,n),m=1:p),n=1:p); i,j,m,n ->1:p , 4d matrix , a,b vector. thank.
i can rid of 2 of for
loops. perhaps 1 of matlab wizards on site can better.
p = 3; = rand(p, p, p, p) = rand(p, 1) b = rand(p, 1) % think original code this. k1 = zeros(p, p); n = 1: p m = 1: p j = 1: p = 1: p k1(i, j) = k1(i, j) + a(m) * b(n) * a(i, j, m, n); end end end end k1 % gives same result, half loops. k2 = zeros(p, p); n = 1: p m = 1: p k2 = k2 + a(m) * b(n) * a(:,:,m,n); end end k2 % verify 2 answers same. all(k1(:) == k2(:))
Comments
Post a Comment