Can I write a function that can create nested loops

1 view (last 30 days)
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 Comments
Dyuman Joshi
Dyuman Joshi on 7 Dec 2022
Which specific cycle time? The code doesn't reflect anything like that.
Ganesh Gudipati
Ganesh Gudipati on 8 Feb 2023
You can try writing a recursive function with single for loop.

Sign in to comment.

Answers (1)

DGM
DGM on 7 Dec 2022
Moved: Jan on 8 Feb 2023
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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!