Replacing nested "for" loops
이전 댓글 표시
Hi all,
I have a set of "K" nested "for" loops, where "K" is variable. An example of my code for when K=4 is as follows:
Spectral_eff_Points=(0):(1):(20);
S=zeros(K,1);
p=zeros(K,1);
n = length(Spectral_eff_Points);
for s1_index=1:n,
S(1)=Spectral_eff_Points(s1_index);
for s2_index=1:n,
S(2)=Spectral_eff_Points(s2_index);
for s3_index=1:n,
S(3)=Spectral_eff_Points(s3_index);
for s4_index=1:n,
S(4)=Spectral_eff_Points(s4_index);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MAIN CALCULATIONS DONE HERE
for user_index=1:K
if user_index==1;
p(user_index)=(2^(S(user_index))-1)* (N/g(user_index));
else
increment=1:(user_index-1);
Sum_P_inc=sum(p(increment));
p(user_index)=(2^(S(user_index))-1)* ((N/g(user_index))+Sum_P_inc);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
end
end
end
As you can see, for large "K" and "n" values, the code will be very very slow :( Does anyone have any better way of conducting such loops, but in a much faster way?!
any help will be much appreciated.
Thanks
채택된 답변
추가 답변 (1개)
Jan
2012년 5월 9일
A code example for K "loops" represented by a [1 x K] vector:
n = 3;
K = 4;
V = ones(1, K);
go = true;
while go
% The action:
disp(V);
% Increment:
V(K) = V(K) + 1;
if V(K) > n
V(K) = 1;
go = false;
for i = K-1:-1:1
V(i) = V(i) + 1;
if V(i) <= n % i.th counter not at limit
go = true;
break; % Leave "for i" loop
end
V(i) = 1; % Reset i.th counter
end
end
end
This is choosing K elements from the vector 1:n with repetition and order.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!