Filter löschen
Filter löschen

Can I write a function that can create nested loops

1 Ansicht (letzte 30 Tage)
arash rad
arash rad am 7 Dez. 2022
Kommentiert: Jan am 8 Feb. 2023
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 Kommentare
Dyuman Joshi
Dyuman Joshi am 7 Dez. 2022
Which specific cycle time? The code doesn't reflect anything like that.
Ganesh Gudipati
Ganesh Gudipati am 8 Feb. 2023
You can try writing a recursive function with single for loop.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

DGM
DGM am 7 Dez. 2022
Verschoben: Jan am 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

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by