Generalize to a number n of FOR-cycles

1 visualizzazione (ultimi 30 giorni)
Sergio Codeluppi
Sergio Codeluppi il 3 Lug 2013
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 Commenti
Guru
Guru il 4 Lug 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
Walter Roberson il 4 Lug 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.

Accedi per commentare.

Risposte (0)

Prodotti

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by