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 CenterFile Exchange에서 MATLAB Coder에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by