Generalize to a number n of FOR-cycles
1 次查看(过去 30 天)
显示 更早的评论
i wrote a program which needs 2*n FOR-cycles and i have to generalize it for a generic n;
if my question wasn't clear, here i brought my problem with n=2 and n=3 with A matrix (n_A x n), phi matrix (n_phi x n), w a vector and
x_i=@(a,b,c) a*cos(b*t+c)
x=[];
if n==2
for jj1=1:n_A
for jj2=1:n_A
for kk2=1:n_phi
for ii=1:n
jj=[jj1 jj2];
kk=[kk2 kk2];
x=x+x_i(A(jj(ii),ii),w(ii),phi(kk(ii),ii));
end
end
end
end
end
if n==3
for jj1=1:n_A
for jj2=1:n_A
for jj3=1:n_A
for kk2=1:n_phi
for kk3=1:n_phi
for ii=1:n
jj=[jj1 jj2 jj3];
kk=[kk2 kk2 kk3];
x=x+x_i(A(jj(ii),ii),w(ii),phi(kk(ii),ii));
end
end
end
end
end
end
end
note that phi(1,:)= 0 that's why i didn't care of kk1
4 个评论
Guru
2013-7-4
t would have to be defined already in the workspace to be referenced within the anonymous function x_i. Is there a particular reason why the Original Poster is using so many nested FOR loops and not just vectorize the whole thing. For that matter, in both cases jj and kk are independent of the loop variable ii and really should be moved outside the loop.
Walter Roberson
2013-7-4
Yes, a lot of vectorization should be done, and initializations should be moved out of loops. The jj and kk are really misdirections selecting one of the outer indices; with a small bit of vectorization they would disappear.
I wonder about the dimensions of the matrix to be produced? I'm thinking in terms of using ndgrid or bsxfun.
回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!