Can I write a function that can create nested loops

1 次查看(过去 30 天)
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
Thanks in advance
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 个评论
Dyuman Joshi
Dyuman Joshi 2022-12-7
Which specific cycle time? The code doesn't reflect anything like that.
Ganesh Gudipati
Ganesh Gudipati 2023-2-8
You can try writing a recursive function with single for loop.

请先登录,再进行评论。

回答(1 个)

DGM
DGM 2022-12-7
移动:Jan 2023-2-8
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

类别

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