passing data to simulink file from workspace in matlab - matlab

I build a model using simulink file , and i used 3 from workspace Block , these Blocks must have a digital data , my question is , how to pass data to the simulink file , from workspace ? i have do the examples that mathwork website give , but the problem is (again) how we pass it to simulink file :
`
t = [0:0.2:10];
x = sin(t);
y = 10*sin(t);
wave.time = t;
wave.signals.values = [x,y];
wave.signals.dimensions =2;`

if you need x,y,t in simulink then you may use:
1.In the MATLAB Command Window, enter:
t = [0:0.2:10]';
x = sin(t);
y = 10*sin(t);
The time vector must be a column vector.
2.Add a 'From Workspace' block to your model.
3.Double-click the block to open the block parameters dialog. In the Data field, enter the array [t,x,y]

Related

Modify Simulink parameters from matlab workspace

I have a program that allows me to transfer all the block parameters from my simulink file to the matlab workspace which is this part :
function TransVar(SimulinkName) %program takes the simulink file name as argument
AE=find_system(SimulinkName); % AE is an array containing in the first cell the name of the
simulink file then the name
% of the blocks in this format : 'SimulinkName/blockName'
for i = 2:length(AE); % i start at 2 because first element of AE is the name of the file
A = strfind(AE{i,1},'/')%find the rank of the / in the string
newName = AE{i,1}(A+1:end);% Gives newName the name of the block
ParList(i-1,1) = {newName}; % Assign the block name to a cell array
assignin('base','ParList',ParList) % Export it to the matlab workspace
newName = regexprep(newName,'\W','');
newName = regexprep(newName,'[éè]','e');
newName = newName(isstrprop(newName,'alphanum'));
ParName(i-1,1) = {newName}; %change the name of the block so that it can be used as a field
assignin('base','ParName',ParName) % export it to the workspace
p = Simulink.Mask.get(AE{i,1});
if isempty(p)
Parametre.(newName) = [];
else
Parametre.(newName)=p.getWorkspaceVariables; %get the variables from the simulink block and
assign it ot the field of it's
%name in the structure parameter
assignin('base','Parametre',Parametre) % Export it to matlab workspace
end
end
Now all the variables have been exported to matlab workspace and can be modified by the user. what i want to do next is once these variables have been changed, I want to be able to change them in the simulink file for that i use this part :
Parametre = evalin('base','Parametre'); %Assign to parameter the struct parameter from the
matlab workspace
ParName = evalin('base','ParName');
ParList = evalin('base','ParList');
%Update the variables in the simulink file
for i = 1:length(fieldnames(Parametre))
if isempty(Parametre.(ParName{i,1})) %if the field has no variables then it will do nothing
and go to the next field
else
for b = 1:length(Parametre.(ParName{i,1}))
if length(Parametre.(ParName{i,1})(b).Value) >= 100 %if one of the variable in the fied has
more than 100 values it won't
% be updated as it is not a usefull one.
else
if isnumeric(get_param([SimulinkName '/' ParList{i,1}],Parametre.(ParName{i,1})(b).Name)) == 0
%if a variables isn't a number
%but a string when imported from simulink then it won't be updated
elseif isempty(Parametre.(ParName{i,1})(b).Value)
set_param([SimulinkName '/' ParList{i,1}],Parametre.(ParName{i,1})(b).Name,'[]')% if variable
is empty it gives the value
% []
save_system([SimulinkName])
else % if the variable in the field has a proper value it will update the one in the simulink
file then save the simulink file
set_param([SimulinkName '/' ParList{i,1}],Parametre.(ParName{i,1})(b).Name,(['['
num2str(Parametre.(ParName{i,1})(b).Value) ']' ]))
save_system([SimulinkName])
end
end
end
end
end
The problem that is faced is that there is no time for the user to actually change the variables in the workspace. And if i try to pause the function with an uiwait the variables cannot be modified in the workspace, you can see them but not acces them.

From Workspace Data Structure

I am importing data from Simulink, flip the data and then try to import the data with the Simulink block:
from workspace
This always returns a error. I tried this, but it doesn't work:
simOut = sim('sim1', Simulation_Time);
t = simOut.P.time;
P_tilde = simOut.P.Data; % size: 2x2x3001
P_data = flip(P_tilde); % size: 2x2x3001, but with the data flipped
P_import = P_data; % import block for 'sim2'
simOut2 = sim('sim2', Simulation_Time);
The error returned:
Unsupported input format for From Workspace block 'sim2/From Workspace'. Available formats are double non-complex matrix, a structure with or without time,
or a structure with MATLAB timeseries as leaf nodes. All formats require the data to be finite (not Inf or NaN).
Does anyone has a idea how to solve it? I have tried and read the description for the "from workspace" block, but I am not any smarter. For example, the functions recommended to use; "timeseries(P_data)" or "timetable(P_data)" do not work and just return errors.
The solution is little bit too complicated, but it works.
I flip each element of mx 2x2xn matrix, then I create a timeseries():
simOut = sim('m2_simP', 'StartTime','0','StopTime', num2str(Simulation_Time),'FixedStep',num2str(Time_Step));
t = simOut.P.time;
P_tilde = simOut.P.Data;
p11 = flip(reshape(P_tilde(1,1,:),[],1));
p12 = flip(reshape(P_tilde(1,2,:),[],1));
p22 = flip(reshape(P_tilde(2,2,:),[],1));
for i = 1:size(t,1)
P_data(1,1,i) = p11(i,1);
P_data(1,2,i) = p12(i,1);
P_data(2,1,i) = p12(i,1);
P_data(2,2,i) = p22(i,1);
end
P_import = timeseries(P_data, t);

How to generate a function inside a script file in MATLAB

I am looking for a way to write a script file in MATLAB that generates a sequence of functions and save them each in a separate m-file.
More precisely, suppose you have a script file and you want to generates N different functions; something like this:
for i=1:N
Step 1: Do some symbolic calculation and find the expression of fi
Step 2: Define the function fi=fi(...)
Step 3: Save the the function in an m-file say fi.m
end
I myself have not found any clue so far. Here is two questions that if answered, such code then follows straightforwardly:
1. How to define a function in a script file and automatically save it in an m-file:
Let say y=f(x)=x^2 is a symbolic relation calculated in a script file; how to automatically generate a function for it and save it in an m-file
2. How to use a string as a file name, function name, etc: Suppose you are creating an string "fi" in a loop for every i, and you want to use this string as a function name
Thanks for your help in advance
https://www.mathworks.com/help/symbolic/matlabfunction.html#bul5mb5-1
If you want to convert symbolic functions to MATLAB function files, MATLAB has a function (called matlabFunction) that does exactly that.
Example from that page:
syms x y z
r = x^2 + y^2 + z^2;
f = matlabFunction(log(r)+r^(-1/2),'File','myfile');
Which creates 'myfile.m':
function out1 = myfile(x,y,z)
%MYFILE
% OUT1 = MYFILE(X,Y,Z)
t2 = x.^2;
t3 = y.^2;
t4 = z.^2;
t5 = t2 + t3 + t4;
out1 = log(t5) + 1.0./sqrt(t5);

MATLAB GUI User Input Update

I have a MATLAB GUI which takes values from the user input , do some calculation based on those and plot them in the GUI.
Everything is all right and working BUT when I change the values in the GUI it does not plot as expected and gives and error of dimension mismatch. However, there is no dimension mismatch and if I go to the script and press run again (the big green arrow) and then click plot again, it plots the values as expected.
I have initialized all of my values that I use but I can not see how can fix this. I need something like update command for all of the script each time I press the 'plot' button.
Any help is appreciated, many thanks!..
CODE:
a = str2double(get(handles.edit14,'String'));
b = str2double(get(handles.edit15,'String'));
c = str2double(get(handles.edit16,'String'));
d = str2double(get(handles.edit18,'String'));
e = str2double(get(handles.edit19,'String'));
f = str2double(get(handles.edit20,'String'));
for Veff=[a:b:c] %user input speeds (a,b,c) (comes from user)
q = 0.5*1.225*(Veff*1000/3600)^2;
F1=q*S; M1=q*S*Cref;
FX1=(F1*coef(:,1)); FZ1=(F1*coef(:,3)); MM1=(M1*coef(:,5));
W=[d*g:e*g:f*g]; %define mass range (d,e,f comes from user)
for lw=1:1:length(W)
XGEquation2max1 = ((((-FB*(Xa-Xb))-(((FX1(12)))*(Za-Zr))-(((FZ1(7))))*(Xa-Xr))-((max(MM1))))./W(lw)) + Xa;
CGPercent(lw,column) = (XGEquation2max1 - Cstart)/Cref * 100;
end
column=column+1;
end
speed_matrix = [a:b:c];
mass_matrix = [d:e:f];
ns = size(speed_matrix);
ns= ns(2);
count5 = 1;
for ns=1:1:ns
hold all
axes(handles.axes4)
plot(CGPercent(:,ns),transpose(mass_matrix)/1000)
count5 = count5 + 1;
end
Main problem is with the variables 'd,e,f' because when I change 'a,b,c' only (i.e speed) there is no problem.

integrating simulink into a matlab script

I have the following problem. I want to integrate a simulink model into a matlab script, to do different things in a loop with the simulink part of the program.
The program below actually does what I was hoping for when I defined the parameters I used into the simulink model in the workspace. But this solution does not satisfy me. I want to pass the parameters as the second value of the sim function. Unfortunately I can't get my head around this. I literally copied the part to create a structure from the matlab site where the following code sample has been given.
myStruct = Simulink.Parameter;
myStruct.Value = struct('number',1,'units',24);
myStruct.CoderInfo.StorageClass = 'ExportedGlobal';
Unfortunately I get the following error Input argument "m_startSpeed" is undefined. because in my script the parameter m_startSpeed is a value which I input when running the script.
function [optBreakPoint] = computeBreakPoint(m_startSpeed, m_endSpeed, m_length)
myStruct = Simulink.Parameter;
myStruct.Value = struct('m' , 1500, 'R' , 0.25, 'mi' , 1, 'f' , 0.1, 'F' , 50000,'BreakForce' , -10, 'startSpeed' , m_startSpeed, 'breakPoint' , m_length);
myStruct.CoderInfo.StorageClass = 'ExportedGlobal';
endSpeed = m_endSpeed;
while(1)
[T, X, Y] = sim('car', myStruct);
optBreakPoint = breakPoint;
break;
end
plot(T, X);
end
How should I solve this problem?
The input structure (i.e. the second input to the sim function), contains information about how to simulate the model (i.e. information from the Model Configuration dialog, or Configuration Set), not parameters of the blocks in the model.
Look at either
>> doc sim
or http://www.mathworks.com/help/simulink/slref/sim.html
for an example of what that structure should look like.
Block parameters are obtained from a workspace - by default the Base Workspace, but you can specify this by changing the models 'SrcWorkspace" parameter.
This property is also discussed on the above documentation pages.