Simulink MATLAB Function for loop

1 回表示 (過去 30 日間)
John
John 2012 年 1 月 12 日
回答済み: Anshuman 2024 年 12 月 11 日
Hi,
I have an aircraft model in a Matlab Function which is called from a matlab function.
What I am trying to achieve at the moment is simply getting a while loop set up in the function which outputs the value y every time the while loop is run through.
Currently the while loop does not output the value for each timestep, it simply jumps to the final limit condition.
Please see the code:
function [y,i] = fcn_06(u)
%#codegen
coder.extrinsic('tic','pause')
%Init
AC_Variables = struct('AC_position',double(zeros(3,1)));
i = 1;
%If AC Mode = 1 Then Initialise and Launch
AC_Variables.AC_position = u;
%Loop
while (i <= 200000)
[z] = calculation_06(AC_Variables);
AC_Variables = z;
y = AC_Variables.AC_position;
i = i + 1;
%pause(1)
end
y = AC_Variables.AC_position;
end
function [z]=calculation_06(AC_Variables)
%#codegen
AC_Variables.AC_position = AC_Variables.AC_position + 10;
z = AC_Variables;
end
How do I set it up to output the value at each step?
Thank you in advance.

回答 (1 件)

Anshuman
Anshuman 2024 年 12 月 11 日
Hello John,
To ensure that the value 'y' is output at each step of the while loop, you'll need to modify the function to store the intermediate results in an array. This way, you can capture the state of 'y' at each iteration. Here’s how you can adjust your code:
  1. Allocate an array to store y for each iteration.
  2. Save the value of y at each iteration in the array.
  3. Return the array containing all intermediate values.
function [y, i] = fcn_06(u)
%#codegen
coder.extrinsic('tic', 'pause')
% Init
AC_Variables = struct('AC_position', double(zeros(3, 1)));
i = 1;
max_iterations = 200000;
% Preallocate y to store results for each iteration
y = zeros(3, max_iterations);
% If AC Mode = 1 Then Initialise and Launch
AC_Variables.AC_position = u;
% Loop
while (i <= max_iterations)
[z] = calculation_06(AC_Variables);
AC_Variables = z;
% Store the current position in y
y(:, i) = AC_Variables.AC_position;
i = i + 1;
% pause(1) % Uncomment if you want to slow down the loop for debugging
end
% Trim y to only include the filled values
y = y(:, 1:i-1);
end
function [z] = calculation_06(AC_Variables)
%#codegen
AC_Variables.AC_position = AC_Variables.AC_position + 10;
z = AC_Variables;
end
Hope it helps!

カテゴリ

Help Center および File ExchangeMATLAB Coder についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by