D for loops concatenated

3 Ansichten (letzte 30 Tage)
Luca  Fenzi
Luca Fenzi am 17 Okt. 2015
Beantwortet: Luca Fenzi am 20 Okt. 2015
I would like to generalize the following codes for dimension D=2:
D=2;
dim=factorial(P-1+D)/(factorial(P-1)*factorial(D));
indexes=zeros(dim,D);
s=0;
for i=1:P
for j=1:i
s=s+1;
indexes(s,:)=[i-j,j-1];
end
end
dimension D=3:
D=3;
dim=factorial(P-1+D)/(factorial(P-1)*factorial(D));
indexes=zeros(dim,D);
s=1;
for i=1:P
for j=1:i
for k=1:j
indexes(s,:)=[i-j,j-k,k-1];
s=s+1;
end
end
end
P can be an arbitrary integer (e.g. P=4).
In other words I would like to create D for loops in such a way that the first loop goes from 1 to P (i=1:P) the second loop from 1 to the previous one (j=1:i) the third one from 1 to the second one (h=1:j) etc.
Thank you in advance.

Akzeptierte Antwort

Jan
Jan am 17 Okt. 2015
D = 3;
dim = factorial(P-1+D)/(factorial(P-1)*factorial(D));
indexes = zeros(dim,D);
v = ones(1, dim);
for s = 1:dim
indexes(s, 1:D-1) = diff(v);
indexes(s, D) = v(D) - 1;
% Update index vector:
found = false;
for k = D:-1:1
v(k) = v(k) + 1;
if k > 1
if v(k) <= v(k - 1)
break; % Exit for k loop
end
v(k) = 1;
end
end
end
Please test and adjust this to your needs. The idea gets clear: Use one loop and a vector of indices, which are incremented according to the rules in each iteration.

Weitere Antworten (1)

Luca  Fenzi
Luca Fenzi am 20 Okt. 2015
Thank you very much for your answer I adjust it in the following way
P=5;
D =3;
dim = nchoosek(P-1+D,D);
indexes = zeros(dim,D);
v = ones(1,D);
for s = 1:dim
indexes(s, 1:D-1) = -diff(v);
indexes(s, D) = v(D) - 1;
% Update index vector:
for k = D:-1:1
v(k) = v(k) + 1;
if k > 1
if v(k) <= v(k - 1);
break; % Exit for k loop
end
v(k) = 1;
end
end
end
Here I add also an other code for general for-loops concatenated
N=P^D;
indexes=zeros(P,D);
row=zeros(1,D);
for s=1:N
indexes(s,:)=row;
%%Updating
%the alghorithm is counting how many indexes arrived to P-1 (Maximum
%degree)
h=0;
while (h<=D-2)&&(row(h+1)==P-1)
h=h+1;
end
if h>0
row(1:h)=zeros(1,h); %Put zero all the values that were P-1
row(h+1)=row(h+1)+1; % add one to the next index.
end
row(1)=mod(s,P);
end
(Please feel free to comment and improve my codes so I can learn something new =) )

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!

Translated by