Matlab script edit - model recognition - matlab

I try to alter the properties of a MatlabFunction on Simulink. The recommended commands here are below.
open_system('my_model');
S = sfroot
B = S.find('Name','myBlockName','-isa','Stateflow.EMChart');
The 'BlockName' is a MatlabFunction on the model my_model. The content of B is '0×1 empty handle' and S.Name gives DefaultBlockDiagram. It seems it does not recognize the opened model.

The correct command is "slroot"

Related

How to write a script for Wolfram SystemModeler to run several simulations?

I want to run around 100 simulations with my model changing two parameters f and TLoadand track the changes on the phase currents currentSensor.i[1] etc.
Now I'm stuck with the documentation on the Wolfram website because there is no definite explanation on how to use scripting with the SystemModeler. I found for example this link on the Wolfram site with some code but no explanation in which commandline I should use it.
I downloaded the WolframScript program and tried to open my model with wolframscript -file SMPM_VoltageSource_Inverter.mo but it says ToExpression::sntx: Invalid syntax in or before ... eventhouh my model simulates totally fine and without any errors in the SimulationCenter.
Can someone explain to me:
Is it possible to write scripts ?
If Yes:
How can I simulate my model?
How can I do a parameter sweep of f and TLoad? Is it as described in the link?
Is it possible to export data of currentSensor.i[1] as a csv-file? And how to?
Thank you for any help!
I don't know about wolfram sorry, but for OpenModelica the following works:
// to load Model from file use
// loadFile("fileName.mo");
loadString("
model M
parameter Real a = 1;
Real x;
equation
x = a * sin(time);
end M;
"); getErrorString();
buildModel(M); getErrorString();
for a in {1,2,3,4} loop
str_a := String(a); getErrorString();
system("./M -override a=" + str_a); getErrorString();
// for windows use
//system("M.exe -override a=" + str_a); getErrorString();
system("mv M_res.mat " + "M_" + str_a + ".mat");
end for;
Put this in a file named for example model.mos and call it from terminal or command line, depending on your os, with omc model.mos if you have OpenModelica installed. this should generate a csv.
EDIT: I realized the original just saves the last value of x, you might want the full output. Therefore i changed the .mos-file. Each different result will be saved in a different file, if you want to change it to csv you just have to change the generated xml.

Editing the Code of a "MATLAB Function" Block in Simulink Programmatically

I'd like to create a simple Simulink model containing a "MATLAB Function" block programmatically -- i.e. using Matlab code.
Thanks to this guide, I've managed to create a new model containing the block:
open_system(new_system('my_system'))
add_block('simulink/User-Defined Functions/MATLAB Function', 'my_system/my_func')
Usually, in order to edit the "MATLAB Function" block's code, one has to "open" the block by double-clicking on it then entering the new code.
However, I would like to set that code programmatically using e.g. set_param() or any relevant function.
For instance, to set the following as the block's code:
function y = fcn(v)
%#codegen
y = 2 * u;
I would like to use something like:
set_param('my_system/my_func', 'Script',...
'function y = fcn(u)\n%#codegen\n\ny = 2 * u;'...
);
I've looked at the output of get_param('my_system/my_func', 'ObjectParameters') and tried to guess which parameter might be used to set the block's function code: So far, I couldn't find any. Therefore, my question is:
Q: Is it possible, using only Matlab commands, to set the code of a "MATLAB Function" block in Simulink?
(As requested by #Ander Biguri, I've moved a solution that worked for me to a separete answer post. If anyone has an alternative/better approach, please feel free to post it as well)
Well, it seems that this question was asked here before. (perhaps formulated differently though?) I've managed to solve my issue using the following code:
sf = sfroot()
block = sf.find('Path','my_system/my_func','-isa','Stateflow.EMChart');
block.Script = sprintf('function y = fcn(u)\n%%#codegen\n\ny = 2 * u;')

Passing a structure of parameters to a Level 1 m-code S-function in Simulink

I am trying to pass a structure of parameters to an S-function in MATLAB. I have a bunch of parameters and I would like to avoid passing them like this:
% The general form of an MATLAB S-function syntax is:
% [SYS,X0,STR,TS,SIMSTATECOMPLIANCE] = SFUNC(T,X,U,FLAG,P1,...,Pn)
I would prefer passing a single structure that includes all of my parameters. I loaded the data into the Model Workspace as:
First I tried ( in response to Phil):
function [sys,x0,str,ts,simStateCompliance]=system1(t,x,u,flag,DATA_HMMWV)
sizes.NumInputs = 2;
also,
But I get this error:
Phil, this is why I tried to add another input port to the S-Function, I thought that it had to go in there.
I also tried:
sizes.NumInputs = 1;
and I get this error:
Also, are you sure that the DATA_HMMWV is a parameter? It looks slightly different than a Param in this window:
NEW:::: 1/25/2016
Phil, the issue is not with my derivative function, the issue is that I am still not passing the structure into the function. Here is a picture. Notice the data is in the Model Workspace and I passed it (DATA_HMMWV) to the function, but when I stop the simulation at line 13 (debugging mode), DATA_HMMWV is not in the function workspace.
If the code continues ( to flag = 1) we get:
If the code continues to run, it crashes with this error:
So, there were not enough input arguments passed to the function. Also, the function is very simple:
%
function sys = mdlDerivatives(t,x,u,DATA_HMMWV)
sys = DATA_HMMWV.g;
% end mdlDerivatives
It just tries to grab a parameter from the structure.
Setup 1: Load the data as a structure into the base workspace and run the simulink model
clear;
clc;
close all
PlantName = 'untitled';
open(PlantName)
TFinal = 10;
load DATA_HMMWV.mat
sim(PlantName, TFinal)
Setup 2:
Setup 3:
When you double click on this model, specify the structure that you would like to pass to the S-function as:
Setup 4: your functions should also have the structure in it:
function [sys,x0,str,ts,simStateCompliance]=system1(t,x,u,flag,DATA_HMMWV)
and any other functions that you need the structure in, for example:
case 1
sys = mdlDerivatives(t,x,u,DATA_HMMWV);
then,
function sys = mdlDerivatives(t,x,u,DATA_HMMWV)
Now, you have passed a strucure to level-1 S-function!

Error in Publishing a code in matlab

I published the following code in Matlab, although the desired output was produces, but along with that it also generated an error while publishing. Any idea why?
%% Gaussian kernel function
% Some text
function t0 = kachra(Param)
t0 = Param;
end
Attached is the Published output.
Thanks
You need to specify an input to your function when publishing.
If you select Edit Publishing Options you see the following GUI:
Modify your expression here and then publish it in order for input arguments to be passed.
You need to configure custom settings to publish your code with output result.
[t0] = kachra(100); %the argument is of your choice.
add your command-line input argument manually here:

Call graph generation from matlab src code

I am trying to create a function call graph for around 500 matlab src files. I am unable to find any tools which could help me do the same for multiple src files.
Is anyone familiar with any tools or plugins?
In case any such tools are not available, any suggestions on reading 6000 lines of matlab code
without documentation is welcome.
Let me suggest M2HTML, a tool to automatically generate HTML documentation of your MATLAB m-files. Among its feature list:
Finds dependencies between functions and generates a dependency graph (using the dot tool of GraphViz)
Automatic cross-referencing of functions and subfunctions with their definition in the source code
Check out this demo page to see an example of the output of this tool.
I recommend looking into using the depfun function to construct a call graph. See http://www.mathworks.com/help/techdoc/ref/depfun.html for more information.
In particular, I've found that calling depfun with the '-toponly' argument, then iterating over the results, is an excellent way to construct a call graph by hand. Unfortunately, I no longer have access to any of the code that I've written using this.
I take it you mean you want to see exactly how your code is running - what functions call what subfunctions, when, and how long those run for?
Take a look at the MATLAB Code Profiler. Execute your code as follows:
>> profile on -history; MyCode; profile viewer
>> p = profile('info');
p contains the function history, From that same help page I linked above:
The history data describes the sequence of functions entered and exited during execution. The profile command returns history data in the FunctionHistory field of the structure it returns. The history data is a 2-by-n array. The first row contains Boolean values, where 0 means entrance into a function and 1 means exit from a function. The second row identifies the function being entered or exited by its index in the FunctionTable field. This example [below] reads the history data and displays it in the MATLAB Command Window.
profile on -history
plot(magic(4));
p = profile('info');
for n = 1:size(p.FunctionHistory,2)
if p.FunctionHistory(1,n)==0
str = 'entering function: ';
else
str = 'exiting function: ';
end
disp([str p.FunctionTable(p.FunctionHistory(2,n)).FunctionName])
end
You don't necessarily need to display the entrance and exit calls like the above example; just looking at p.FunctionTable and p.FunctionHistory will suffice to show when code enters and exits functions.
There are already a lot of answers to this question.
However, because I liked the question, and I love to procrastinate, here is my take at answering this (It is close to the approach presented by Dang Khoa, but different enough to be posted, in my opinion):
The idea is to run the profile function, along with a digraph to represent the data.
profile on
Main % Code to be analized
p = profile('info');
Now p is a structure. In particular, it contains the field FunctionTable, which is a structure array, where each structure contains information about one of the calls during the execution of Main.m. To keep only the functions, we will have to check, for each element in FunctionTable, if it is a function, i.e. if p.FunctionTable(ii).Type is 'M-function'
In order to represent the information, let's use a MATLAB's digraph object:
N = numel(p.FunctionTable);
G = digraph;
G = addnode(G,N);
nlabels = {};
for ii = 1:N
Children = p.FunctionTable(ii).Children;
if ~isempty(Children)
for jj = 1:numel(Children)
G = addedge(G,ii,Children(jj).Index);
end
end
end
Count = 1;
for ii=1:N
if ~strcmp(p.FunctionTable(ii).Type,'M-function') % Keep only the functions
G = rmnode(G,Count);
else
Nchars = min(length(p.FunctionTable(ii).FunctionName),10);
nlabels{Count} = p.FunctionTable(ii).FunctionName(1:Nchars);
Count = Count + 1;
end
end
plot(G,'NodeLabel',nlabels,'layout','layered')
G is a directed graph, where node #i refers to the i-th element in the structure array p.FunctionTable where an edge connects node #i to node #j if the function represented by node #i is a parent to the one represented by node #j.
The plot is pretty ugly when applied to my big program but it might be nicer for smaller functions:
Zooming in on a subpart of the graph:
I agree with the m2html answer, I just wanted to say the following the example from the m2html/mdot documentation is good:
mdot('m2html.mat','m2html.dot');
!dot -Tps m2html.dot -o m2html.ps
!neato -Tps m2html.dot -o m2html.ps
But I had better luck with exporting to pdf:
mdot('m2html.mat','m2html.dot');
!dot -Tpdf m2html.dot -o m2html.pdf
Also, before you try the above commands you must issue something like the following:
m2html('mfiles','..\some\dir\with\code\','htmldir','doc_dir','graph','on')
I found the m2html very helpful (in combination with the Graphviz software). However, in my case I wanted to create documentation of a program included in a folder but ignoring some subfolders and .m files. I found that, by adding to the m2html call the "ignoreddir" flag, one can make the program ignore some subfolders. However, I didn't find an analogue flag for ignoring .m files (neither does the "ignoreddir" flag do the job). As a workaround, adding the following line after line 1306 in the m2html.m file allows for using the "ignoreddir" flag for ignoring .m files as well:
d = {d{~ismember(d,{ignoredDir{:}})}};
So, for instance, for generating html documentation of a program included in folder "program_folder" but ignoring "subfolder_1" subfolder and "test.m" file, one should execute something like this:
m2html( 'mfiles', 'program_folder', ... % set program folder
'save', 'on', ... % provide the m2html.mat
'htmldir', './doc', ... % set doc folder
'graph', 'on', ... % produce the graph.dot file to be used for the visualization, for example, as a flux/block diagram
'recursive', 'on', ... % consider also all the subfolders inside the program folders
'global', 'on', ... % link also calls between functions in different folders, i.e., do not link only the calls for the functions which are in the same folder
'ignoreddir', { 'subfolder_1' 'test.m' } ); % ignore the following folders/files
Please note that all subfolders with name "subfolder_1" and all files with name "test.m" inside the "program_folder" will be ignored.