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!