for loop as matlab function in simulink

4 Ansichten (letzte 30 Tage)
vishnuvardhan naidu tanga
vishnuvardhan naidu tanga am 12 Dez. 2019
Beantwortet: Riya am 31 Mär. 2025
Hello is there any way to do for loop as a matlab function in simulink. my code is as follows:
P=zeros(1,n+1 );
P(1) = P_in ;
CR = (P_out/P_in)^(1/n);
for i = 2:n
P(i) = CR*P(i-1 );
P(i+1) = CR*P(i );
end
T=zeros(1,n);
for i = 1:n-1
T(i) = ((P(i+1)/P_in)*(T_in^(kappa/(kappa-1))))^((kappa-1)/kappa);
T(i+1) = ((P(i+1)/P(i))*(T(i)^(kappa/(kappa-1))))^((kappa-1)/kappa);
end
running=zeros(n,1);
for i=1:n
running(i)=((P(i+1)/P(i))^((kappa-1)/kappa));
end
W = (kappa*M)/(kappa-1)*((sum(running))-n);
is there any way to solve this in simulink?

Antworten (1)

Riya
Riya am 31 Mär. 2025
Hi Vishnuvardhan,
I understand that you are trying to implement a for loop as a MATLAB function into Simulink.
When working with iterative computations in Simulink, the best approach is to use a MATLAB Function block, which allows you to embed MATLAB code into the Simulink model.
Refer to the following steps for the same:
1. Open Simulink and create a new model.
2. Add a MATLAB Function block from the Simulink Library.
3. Replace the existing code in the block with the following function:
function W = for_loop_simulink(n, P_in, P_out, T_in, kappa, M)
% Initialize arrays
P = zeros(1, n+1);
T = zeros(1, n);
running = zeros(n,1);
% Set initial values
P(1) = P_in;
CR = (P_out/P_in)^(1/n);
% Compute pressure values
for i = 2:n
P(i) = CR * P(i-1);
P(i+1) = CR * P(i);
end
% Compute temperature values
for i = 1:n-1
T(i) = ((P(i+1)/P_in) * (T_in^(kappa/(kappa-1))))^((kappa-1)/kappa);
T(i+1) = ((P(i+1)/P(i)) * (T(i)^(kappa/(kappa-1))))^((kappa-1)/kappa);
end
% Compute running sum
for i = 1:n
running(i) = ((P(i+1)/P(i))^((kappa-1)/kappa));
end
% Compute final result
W = (kappa * M) / (kappa-1) * ((sum(running)) - n);
end
Here, the inputs are n, P_in, P_out, T_in, kappa, M” and the output is “W.
4. Now, connect input signals to the MATLAB Function Block.
5. Finally, run the simulation and verify the output obtained.
This method allows you to efficiently implement the required “for loop logic inside Simulink.
For further reference about MATLAB Function block, refer to the official MATLAB documentation below:

Kategorien

Mehr zu Simulink finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by