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

1 回表示 (過去 30 日間)
Rangga
Rangga 2023 年 2 月 3 日
編集済み: Rangga 2023 年 2 月 11 日
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

採用された回答

Voss
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_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 件のコメント
Rangga
Rangga 2023 年 2 月 6 日
編集済み: Rangga 2023 年 2 月 6 日
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 2023 年 2 月 6 日
編集済み: Rangga 2023 年 2 月 11 日
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!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by