Function with varying number of for loops

조회 수: 8 (최근 30일)
Mitchell Morin
Mitchell Morin 2017년 6월 20일
답변: Jan 2017년 6월 20일
My input is a number (most likely between 1 and 5) and I need a code to create n number of for loops with my output in the last for loop. Each dimension would have length 14, so in total there would be 14^n values
Something like this
n=1
for a=1:14
Output(a)=1 or 0
end
n=2
for a=1:14
for b=1:14
Output(a,b)=1 or 0
end
end
It has to create each for loop and not just an empty array of dimensions n
Any help would be appreciated, thank you in advance!

답변 (1개)

Jan
Jan 2017년 6월 20일
Do not use a bunch of nested for loops, but an index vector and one loop:
n = 5; % Number of loops
v = ones(1, n); % Index vector
Output = zeros(repmat(14, n));
ready = false;
while ~ready
index = sub2ind(size(Output), v);
Output(index) = 1 or 0 ???
% Update the index vector:
ready = true; % Assume that the WHILE loop is ready
for k = 1:n
v(k) = v(k) + 1;
if v(k) <= 14
ready = false;
break; % v(k) increased successfully, leave "for k" loop
end
v(k) = 1; % v(k) reached the limit, reset it
end
end

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by