Creating variable number of for loops

I'm trying to create variable number of nested for loop depending on the length of vector. The length of each for loop depends on the number in that particular column of the vector. So for example:
if a = [2 3 3];
for i = 1:2
for j = 1:3
for k = 1:3
do something
end
end
end
I have looked around and it seems that recursive function is the best way to go about this. I know how to use a recursive function to replace a for loop but after that I'm not sure how to procede.
Here is a sample of my recursive code to replace a single for loop.
function result = h(x1)
% abc = 0;
if x1 <= 0
result = 1;
else
result = 2*h(x1-1);
end
Any help would be appreciated. Thanks!

1 件のコメント

Adam Danz
Adam Danz 2020 年 4 月 3 日
What's happening in do-something? If it's short, provide the code. If it's more than a dozen lines, a short description would due.

サインインしてコメントする。

 採用された回答

Sean de Wolski
Sean de Wolski 2015 年 3 月 23 日

0 投票

I would just use two loops, one to loop over a and one to loop on each element of a:
a = [2 3 3];
for aloop = 1:numel(a)
for ii = 1:a(ii)
do whatever
end
end

2 件のコメント

Raphaël Fua
Raphaël Fua 2020 年 4 月 3 日
What will a(ii) be ?
Stephen23
Stephen23 2020 年 4 月 3 日

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by