How do i connect and running different loop at the same time?
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
please help, i want to run Loop 1 (i.e: n=2) but the equation need output from Loop 2 (n = n-1), so while i calculate Loop 1 i need data from Loop 2 that running at the same time.
i planning to put another Loop 3 to y.
t actually is time domain in my equation.
How can i connect those two loops? should i use another way?
clear
clc
t = linspace(0,10,5);
y = [ 3 2 1 4 5 ];
rudAngle0 = 0;
% 1st Loop
for n = [ 1:length(t) ]
disp("running " + n)
indexnya = n;
if n == 1
disp("output running " + n)
L = rudAngle0;
else
disp("output running " + n)
L = final_loop1(n-1) + final_loop2(n-1)
end
final_loop1(n) = L
end
% 2nd Loop
for n = [ 1:length(t) ]
disp("running " + n)
indexnya = n;
if n == 1
disp("output running " + n)
L = 0;
else
disp("output running " + n)
L = final_loop1(n-1) + y(n-1)
end
final_loop2(n) = L
end
0 commentaires
Réponse acceptée
Voss
le 3 Fév 2023
Combine the two loops into one loop, so that they actually run at the same time:
t = linspace(0,10,5);
y = [ 3 2 1 4 5 ];
rudAngle0 = 0;
nt = length(t);
final_loop1 = zeros(1,nt); % pre-allocate
final_loop2 = zeros(1,nt);
% Loop
for n = 1:nt
if n == 1
L1 = rudAngle0;
L2 = 0;
else
L1 = final_loop1(n-1) + final_loop2(n-1);
L2 = final_loop1(n-1) + y(n-1);
end
final_loop1(n) = L1;
final_loop2(n) = L2;
end
final_loop1
final_loop2
You can simplify that loop by setting the first element of each vector before the loop, and then start the loop with n=2, and also get rid of temporary variables L1 and L2 by setting final_loop1(n) and final_loop2(n) directly:
t = linspace(0,10,5);
y = [ 3 2 1 4 5 ];
rudAngle0 = 0;
nt = length(t);
final_loop1 = zeros(1,nt); % pre-allocate
final_loop2 = zeros(1,nt);
final_loop1(1) = rudAngle0;
final_loop2(1) = 0;
% Loop
for n = 2:nt
final_loop1(n) = final_loop1(n-1) + final_loop2(n-1);
final_loop2(n) = final_loop1(n-1) + y(n-1);
end
final_loop1
final_loop2
2 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!