Creating nested MATLAB function in simulink

Hi,
I have written a sample matlab script which contains nested for loops(one inside another, given below). But I want to implemt this code in simulink with two MATLAB function blocks, say function 1 and function 2. function 1 has to calculate the inner loop and function 2 has to calculate the outer loop. function 1 has one output = i_global, no inputs, and function 2 has one input = i_global, and no outputs.
So I want to run this two function blocks like the below code such that, after updating each x value, function 2 must generate y values(4 times, as per the inner loop). i.e when x(1)=1, then next output in the terminal should be y(1)=2,y(2)=3,y(3)=4,y(4)=5, then it has to exit its loop (inner loop of function 2) and continue function 1 with i_global=2.
Any help would be appreciated.
Thanks in advance
Hashir
j = 4;
Ts=0.1;
t = 0:Ts*j:100;
len = length(t);
a=1;
b=2;
x=zeros(1,len-1);
y=zeros(1,len-1);
for i_global = 1:len-1 % outer loop
x(i_global) = a;
a=a+1;
for i=1:j % inner loop
y(i_global) = b;
b=b+1;
end
end

Réponses (1)

The solution is simple. Construct two functions with approriate inputs and outputs. Assume all variables necessry are passed to the function.
j = 4;
Ts=0.1;
t = 0:Ts*j:100;
len = length(t);
a=1;
b=2;
x=zeros(1,len-1);
y=zeros(1,len-1);
[x, y] = function1(a, b, j, x ,y, len);
function [x, y] = function1(a, b, j, x, y, len)
for i_global = 1:len-1
x(i_global) = a;
a = a + 1;
y = function2(b, j, y, i_global);
end
end
function [y] = function2(b, j, y, i_global)
for i=1:j
y(i_global) = b;
b = b + 1;
end
end

1 commentaire

VAHA
VAHA le 8 Août 2022
Hey Mr Manas, Thanks for the answer, but my question is not about writing two functions in Matlab code, rather implementing those algorithm in simulink using two simulink function blocks.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Modeling dans Centre d'aide et File Exchange

Question posée :

le 6 Août 2022

Commenté :

le 8 Août 2022

Community Treasure Hunt

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

Start Hunting!

Translated by