How do i connect and running different loop at the same time?

5 vues (au cours des 30 derniers jours)
Rangga
Rangga le 3 Fév 2023
Modifié(e) : Rangga le 11 Fév 2023
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

Réponse acceptée

Voss
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_loop1 = 1×5
0 0 3 5 9
final_loop2
final_loop2 = 1×5
0 3 2 4 9
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_loop1 = 1×5
0 0 3 5 9
final_loop2
final_loop2 = 1×5
0 3 2 4 9
  2 commentaires
Rangga
Rangga le 6 Fév 2023
Modifié(e) : Rangga le 6 Fév 2023
thanks a lot! it works in my code!
but i change my t to [1:700] and after the 6th loop and later it shows NaN
Rangga
Rangga le 6 Fév 2023
Modifié(e) : Rangga le 11 Fév 2023
and also it open workspacefunc.m and display this on command window
NaN/Inf breakpoint hit for workspacefunc.m on line 310.
310 v = evalin('caller', varargin{1});
UPDATE
never mind, i got the code work, thanks!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by