How do i connect and running different loop at the same time?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Voss
2023-2-3
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!