Generalize to a number n of FOR-cycles
Show older comments
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 Comments
Jan
on 3 Jul 2013
What is the logic behind "kk=[kk2 kk2];" and "kk=[kk2 kk2 kk3];"? What will appear for n==4?
Walter Roberson
on 4 Jul 2013
Is the pattern that the first n loops run to n_A, the next (n-1) loops run to n_phi, and the last loop runs to n ? And that no matter what n is, that x_i() will take three arguments?
Where is "t" defined? It is used in x_i() but does not otherwise show up in your code.
Guru
on 4 Jul 2013
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
on 4 Jul 2013
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.
Answers (0)
Categories
Find more on MATLAB Coder in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!