# Can I write a function that can create nested loops

1 回表示 (過去 30 日間)
arash rad 2022 年 12 月 7 日
コメント済み: Jan 2023 年 2 月 8 日
Hello everyone
I wrote a code that has multiple for loops inside each other in the code below but i try to write a function to create this multiple for loops but I don't know how to this can anyone help me
my for loops is :
qd(:,1) = Ftu(1).*qu(1);
for i = 2:7
qd(:,i) = (1 - Ftu(i))*qd(:,i-1) + Ftu(i).*qu(i);
if i == 7
for i = 8:14
qd(:,i) = (1 - Ftu(i))*qd(:,i-1) + Ftu(i).*qu(i);
if i == 14
for i = 15:21
qd(:,i) = (1 - Ftu(i))*qd(:,i-1) + Ftu(i).*qu(i);
if i == 21
for i = 22:28
qd(:,i) = (1 - Ftu(i))*qd(:,i-1) + Ftu(i).*qu(i);
if i == 28
for i = 29:35
qd(:,i) = (1 - Ftu(i))*qd(:,i-1) + Ftu(i).*qu(i);
if i == 35
for i =36:42
qd(:,i) = (1 - Ftu(i))*qd(:,i-1) + Ftu(i).*qu(i);
if i == 42
for i = 43:49
qd(:,i) = (1 - Ftu(i))*qd(:,i-1) + Ftu(i).*qu(i);
end
end
end
end
end
end
end
end
end
end
end
end
end
##### 4 件のコメント2 件の古いコメントを表示2 件の古いコメントを非表示
Dyuman Joshi 2022 年 12 月 7 日
Which specific cycle time? The code doesn't reflect anything like that.
Ganesh Gudipati 2023 年 2 月 8 日
You can try writing a recursive function with single for loop.

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

### 回答 (1 件)

DGM 2022 年 12 月 7 日

rng(123) % make sure inputs are repeatable
Ftu = rand(1,49);
qu = rand(1,49);
qd = zeros(1,49); % preallocate
qd(:,1) = Ftu(1).*qu(1);
for i = 2:7
qd(:,i) = (1 - Ftu(i))*qd(:,i-1) + Ftu(i).*qu(i);
if i == 7
for i = 8:14
qd(:,i) = (1 - Ftu(i))*qd(:,i-1) + Ftu(i).*qu(i);
if i == 14
for i = 15:21
qd(:,i) = (1 - Ftu(i))*qd(:,i-1) + Ftu(i).*qu(i);
if i == 21
for i = 22:28
qd(:,i) = (1 - Ftu(i))*qd(:,i-1) + Ftu(i).*qu(i);
if i == 28
for i = 29:35
qd(:,i) = (1 - Ftu(i))*qd(:,i-1) + Ftu(i).*qu(i);
if i == 35
for i =36:42
qd(:,i) = (1 - Ftu(i))*qd(:,i-1) + Ftu(i).*qu(i);
if i == 42
for i = 43:49
qd(:,i) = (1 - Ftu(i))*qd(:,i-1) + Ftu(i).*qu(i);
end
end
end
end
end
end
end
end
end
end
end
end
end
% the exact same thing
rng(123) % make sure inputs are repeatable
Ftu = rand(1,49);
qu = rand(1,49);
qd2 = zeros(1,49); % preallocate
qd2(:,1) = Ftu(1).*qu(1);
for i = 2:49
qd2(:,i) = (1 - Ftu(i))*qd2(:,i-1) + Ftu(i).*qu(i);
end
immse(qd,qd2) % the results are identical
ans = 0
##### 1 件のコメント-1 件の古いコメントを表示-1 件の古いコメントを非表示
Jan 2023 年 2 月 8 日
Wow. This looks cleaner :-)

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

### カテゴリ

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