How to automatically introduce a nested layer of for-loop?

2 ビュー (過去 30 日間)
Wh Khu
Wh Khu 2019 年 2 月 26 日
回答済み: Shunichi Kusano 2019 年 2 月 26 日
Given a set of x-values , I want to create a script that generates a product of n numbers.
For example, if I want to generate products of 2 numbers, i.e. and so on, the script would be:
for i_1=1:3
for i_2=1:3
Product=X(i_1)*X(i_2)
end
end
There will be 2 for-loops, one nested in another.
If I want to generate products of 3 numbers, i.e. and so on, the script would be:
for i_1=1:3
for i_2=1:3
for i_3=1:3
Product=X(i_1)*X(i_2)*X(i_3)
end
end
end
There will be 3 for-loops, i.e. 2 nested loops in an external loop.
Is there a way to automate this, like a recursion, so when n increases, it will automatically introduce a nested for-loop in the original script? The concept is like this:
n=n
for i_1=1:3
for i_2=1:3
for i_3=1:3
.
.
.
for i_n=1:3
Product=X(i_1)*X(i_2)*X(i_3)*...*X(i_n)
end
.
.
.
end
end
end
  2 件のコメント
Yasasvi Harish Kumar
Yasasvi Harish Kumar 2019 年 2 月 26 日
編集済み: Yasasvi Harish Kumar 2019 年 2 月 26 日
The Product variable gets over written in each iteration. I dont see why you would have a loop for it.
If you still need to write multiple loops, try recursive function as a solution.
Wh Khu
Wh Khu 2019 年 2 月 26 日
編集済み: Wh Khu 2019 年 2 月 26 日
I know my Product will get overwritten for every loop, so I'm gonna store it into a cell for each iteration, it's just that I don't want to include that unrelated intricacy in my example above because that's not the point. I want to simplify the bigger picture, which is to add nested for-loops automatically based on the number n I assign.

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

採用された回答

Shunichi Kusano
Shunichi Kusano 2019 年 2 月 26 日
Hi, This is a possibility:
N = 4; % the loop number
X = rand(1,3); % simulated X
products = ones(ones(1,N)*3);
reshape_arr = [3 ones(1,N-1)];
repmat_arr = [1 ones(1,N-1)*3];
for i = 1:N
temp = repmat(reshape(X, circshift(reshape_arr, i-1)), circshift(repmat_arr,i-1));
products = products .* temp;
end
hope this helps.

その他の回答 (0 件)

カテゴリ

Help Center および 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