Borrar filtros
Borrar filtros

Can I write a function that can create nested loops

1 visualización (últimos 30 días)
arash rad
arash rad el 7 de Dic. de 2022
Comentada: Jan el 8 de Feb. de 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 comentarios
Dyuman Joshi
Dyuman Joshi el 7 de Dic. de 2022
Which specific cycle time? The code doesn't reflect anything like that.
Ganesh Gudipati
Ganesh Gudipati el 8 de Feb. de 2023
You can try writing a recursive function with single for loop.

Iniciar sesión para comentar.

Respuestas (1)

DGM
DGM el 7 de Dic. de 2022
Movida: Jan el 8 de Feb. de 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

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by