Nested for loop from variables

조회 수: 1 (최근 30일)
Md Arif Ahmed Roni
Md Arif Ahmed Roni 2020년 10월 1일
답변: Ameer Hamza 2020년 10월 1일
Hello
I have a following code:
L1 = {'150um', '250um', '350um'};
W1 = {'250um'};
W2 = {'30um'};
for aa = 1:length(L1)
for bb = 1:length(W1)
for cc = 1:length(W2)
some task
end
end
end
At the moment i have 3 for loops for 3 variables (L1, W1, W3). This will change and can be any number of variables. So now how can i make the for loop adapt to that automatically?

답변 (1개)

Ameer Hamza
Ameer Hamza 2020년 10월 1일
L1 = {'150um', '250um', '350um'};
W1 = {'250um'};
W2 = {'30um'};
C = {L1, W1, W2}; % pack all varaibles in a cell array
[C{:}] = ndgrid(C{:});
C = [C{:}];
for i = 1:size(C, 1) % just iterate over rows of C
l = C{i, 1};
w1 = C{i, 2};
w2 = C{i, 2};
% some task
end

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by