How can I pass a piecewise-defined function to Simulink?
Ältere Kommentare anzeigen
I'm building a Simulink model in which I have to solve 3 coupled differential equations. In one of these, I need to use a function f(x) whose form isn't known: I just know its values at some points (the values of this function are written in a file produced by another program); that is, I have quite a big number of couples (x, y(x)). I wouldn't like to fit these points with a polynomial funtion and pass the coefficients valued to a 'polyval' block; on the contrary, I'd like to use a linear interpolation among the various points, because, in this case, it is probably way more faithful to the true behaviour of the function (suppose for instance that the function has some sharp edges: a polynomial would fit well those values only if it is a very high degree polynomial). I wrote down the code to perform this interpolation in MATLAB, but then I don't know how to pass this function to Simulink.
My code is the following:
fopen(filename, 'r');
formatSpec = '%f %f';
sizeA = [Inf 2];
A = fscanf(filename, formatSpec, sizeA);
fclose(filename);
y_p=A[:,2];
x_p=A[:,1];
syms x;
if (x<x_p(1))
f(x)=y_p(1)+(x-x_p(1))*((y_p(2)-y_p(1))/(x_p(2)-x_p(1)));
elseif (x>x_p(length))
f(x)=y_p(length(x_p))+(x-x_p(length(x_p)))*((y_p(length(x_p))-y_p(length(x_p)))/(x_p(length(x_p))-x_p(length(x_p)-1)));
else
for i=1:(length(x_p)-1)
if ((x>x_p(i))&&(x<x_p(i+1)))
f(x)=(y_p(i))+((y_p(i+1)-y_p(i))/(x_p(i+1)-x_p(i)))*(x-x_p(i));
elseif (x==x_p(i))
f(x)=y_p(i);
end
end
end
Should I use the S-function block? The problem is, if I call this code through the S-function block in Simulink, I fear it's going to take too much time to open, copy the values in memory and close the file, resulting in a long simulation time. Is there a way I can manage to save "permanently" in memory the values read from the data file?
I obviously welcome other ideas!
Thanks in advance.
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Simulink Functions finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!