Automatically generating a diagram of function calls in MATLAB [closed] - matlab

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
Anybody knows of a tool that can be used to automatically build diagrams of function calls in MATLAB?
E.g. For a given function, the tool would recursively go through function calls and build a 2D graph where nodes would represent functions and directed edges would connect calling functions with called functions.
Ideally the tool could allow the user to turn on and off filters to only include user-defined functions, limit the depth of recursion, etc.
I believe Doxygen provides some similar functionality for more traditional OOP languages, but I was wondering if something like this exists already for MATLAB.
Thanks!

You can use the techniques from those other answers referenced in gnovice's comment to get a list of function dependencies as (A,B) pairs, where A calls B. Then install GraphViz and use it to generate the diagrams. You can create the .dot files from Matlab with something like this.
function createFunctionDependencyDotFile(calls)
%CREATEFUNCTIONDEPENDENCYDOTFILE Create a GraphViz DOT diagram file from function call list
%
% Calls (cellstr) is an n-by-2 cell array in format {caller,callee;...}.
%
% Example:
% calls = { 'foo','X'; 'bar','Y'; 'foo','Z'; 'foo','bar'; 'bar','bar'};
% createFunctionDependencyDotFile(calls)
baseName = 'functionCalls';
dotFile = [baseName '.dot'];
fid = fopen(dotFile, 'w');
fprintf(fid, 'digraph G {\n');
for i = 1:size(calls,1)
[parent,child] = calls{i,:};
fprintf(fid, ' "%s" -> "%s"\n', parent, child);
end
fprintf(fid, '}\n');
fclose(fid);
% Render to image
imageFile = [baseName '.png'];
% Assumes the GraphViz bin dir is on the path; if not, use full path to dot.exe
cmd = sprintf('dot -Tpng -Gsize="2,2" "%s" -o"%s"', dotFile, imageFile);
system(cmd);
fprintf('Wrote to %s\n', imageFile);
GraphViz works great for lots of other tree and graph applications, like class inheritance and dependency trees, data flow, and so on.

Related

Changing function variable to another variable MATLAB [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
Is there a way to change a function variable to another variable?
for instance, if I have the function:
f = #(s) exp(2-s)
I need to change it to
f = #(t) exp(2-t)
without changing it manually.
With the usual caveats that this is a terrible idea :) let's get a little nuts.
First, we can make the anonymous function f
f = #(s) exp(2-s)
For some sample uses, for sanity
f(1) % 2.71828182845905
f(10) % 0.000335462627902512
Now, save it to a file, using the -v7.3 flag to force an H5 file type
save('tempfile','f','-v7.3')
Matlab can read this file as data. After some exploring, we can see that the function is stored, as an evaluation-ready string, here:
char(h5read('tempfile.mat','/f/function_handle/function'))
% Returns 'sf%0#(s)exp(2-s)'
So, it's easy enough to change, using Matlab's H5 write functions
h5write('tempfile.mat','/f/function_handle/function',uint16('sf%0#(x)exp(2-x)'))
Let's see, did it work?
clear f
load('tempfile.mat')
Now we have the following
f =
function_handle with value:
#(x)exp(2-x)
f(1) % 2.71828182845905
f(10) % 0.000335462627902512
Now, we can see a lot of this data without the file saving business, using the functions function. (So meta)
>> f = #(s) exp(2-s);
>> functions(f)
ans =
struct with fields:
function: '#(s)exp(2-s)'
type: 'anonymous'
file: ''
workspace: {[1×1 struct]}
within_file_path: '__base_function'
This lets you see how Matlab is storing the anonymous function. When debugging, this allows you to see what baggage (stored workspaces and stuff) is associated with the function handle.
However, changes to this structure do not change the actual function handle. I don't know of a way to generate a new function handle from this structure.
Wrap up
[note #1 deleted]
Please, don't ever do this.

Dont understand the function of cmd_data(ii) = cell2mat(textscan(char(data{i}(ALL_STRT(ii):(ALL_STRT(ii)+4))),'%f')); at all [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
IND_STRT = 0;
ALL_STRT = IND_STRT:12:510;
cmd_data = zeros(length(ALL_STRT),1); %example: x=zeros(1,21) gives you a 1 by 21 matrix
for ii = 1:length(ALL_STRT) %declare variable ii to run from the row of length
if ~isempty(data{i})
cmd_data(ii) = cell2mat(textscan(char(data{i}(ALL_STRT(ii):(ALL_STRT(ii)+4))),'%f'));
end
end
I need to read the EPS from EnduroSat, however i have difficulty understanding the line cmd_data(ii) = cell2mat(textscan(char(data{i}(ALL_STRT(ii):(ALL_STRT(ii)+4))),'%f'));
Im required to utilised MatLab to code and this particular line have an error and i don't understand why.
Whenever you see a complicated line like this in MATLAB, try to break it up.
% find some indices. These values have been selected by the programmer/data, can't say why.
a=ALL_STRT(ii):(ALL_STRT(ii)+4)
% obtain that articular section of the data
b=data{i}(a)
% convert it to a char data type (characters)
c=char(b)
% scan text, and treat them as float
d=textscan(c,'%f')
% the output is a cell array, we want a matrix instead. Make the cell array into a matrix.
cmd_data(ii) = cell2mat(d)
You can read particularly what each of these do better in their documentation pages, and you can see it work if you put a break-point in the code, and see what each of this parts output when you call it. Learn how to debug, is a very very powerful tool

Live display of variables during MATLAB simulation [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I have a simulation which has numerous iterations. There are variable matrices whose values I would like to monitor while the simulation is happening. What are good ways of doing this?
I have two tools that I regularly use for something like this.
1. Iterative output that erases with each iteration
This works well for an optimization where you have a scalar function output you want to monitor.
Before my while loop, I'll define screenOut = []; and an output formula in screenOutFormat. In my loop after the computation has happened for that iteration, I'll put something like
if iter <=2
bspace = [];
else
bspace = repmat('\b', [1 length(screenOut)]);
end
screenOut = sprintf(screenOutFormat, iter, estimatedValue);
fprintf([bspace screenOut]);
This way you get to see the starting point and each iteration without destroying your command window history.
2. Dynamic updates to a figure
This works well if you have something you can plot.
Before the loop begins, set up a plot with
figH = figure();
progPlot = plot(Y);
Then with each iteration you can do
progPlot.YData = Y;
drawnow();
This way you continue plotting the estimate you care about.
If you have a matrix that you care about, I'd recommend picking off the elements that you're really interested in and using #1. But if there's something more useful you can plot, #2 is usually more interesting to watch during long estimation/simulation routines.

Can Matlab optimize an external process? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm considering buying Matlab Home + Optimization module for home use, however I'm not sure it can do what I want it to.
I have an external process (not Matlab) that takes input, runs a process, and produces output. I want to tie in the input and output to Matlab so that Matlab can "optimize" these inputs, completely blind to the discrete process itself. Does Matlab have discrete optimization capabilities, or do all of its optimization functions rely on having internal access to the process itself?
Thanks!
-Stephen
if your external process is capable to assimilate parameters and give response to a external program using any methods eg, command line, or files, yes it is possible just configure your objective function to send and read the parameters and response data to the external process.
For the discrete optimization, the optimization toolbox do not work with discrete optimizations problems, but the documentation give a hint about rounding the parameter inside the objective function and then running again in the responses variable.
for example, this can be a function to optimize a volume of a prism
which is coded in a external program written in python (just for demonstration purpose with single objetive genetic algorithm (ga)):
function f = optim(x)
%Optimization criteria
l = round(x(1));
h = round(x(2));
w = round(x(3));
%String to produce the external proccess call as a system command
commandStr = ['python -c "print ' num2str(l) ' * ' num2str(h) ' * ' num2str(w) ' "'];
%Execute the system command, status = 0 for good execution
[status, commandOut] = system(commandStr);
%Convert the output of the external program from strin to doble and assign as the response of the optimization funcition
f = str2double(commandOut)
Then you can use the optimtool using this funcion as objetive as:
Then export the result to workspace and round() it.
Or make it programmable with a code like this:
function [x,fval] = runOptimization(lb,ub)
options = gaoptimset;
options = gaoptimset(options,'Display', 'off');
[x,fval] =ga(#optim,3,[],[],[],[],lb,ub,[],[],options);
x = round(x)
fval = optim(x)
And run as
[x,fval] = runOptimization([1 1 1],[3 4 5])
NOTE. the round() functions its only to demonstrate how to do discrete optimization as suggested in the documentation

Import text file as a matrix in a matlab script [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Hi everybody I need to automaticly import certain text files stored in my computer as matrices when I run my script in matlab. How do I do that? Thanks
Although the question shows little effort I am reminded how I started out with no knowledge about input or output whatsoever, it is a quite dense forest of information really.
Basically to read a file you need to:
Open the file
Read the file and assign it to a variable
Close the file
Some functions in MatLab take care of all three steps:
importdata
csvread
dlmread
The functions above are suitable if you have very neat and uniform data. Click the links to read if they are suitable for you. If your data is less uniform, e.g. it contains both numbers and letters, you might want to consider textscan.
Using textscan you must carry out all three steps yourself. First open your file and create a link to your file called a file ID (FID):
FID = fopen('mytextfile.txt')
Next you define a format specifier which describes a single line of data (a row).
formatSpec = '%f %f %f %f %s'
This format specifier represents 4 decimal numbers (floats) followed by a string all seperated by whitespace. For more information on the format specifier see:
http://www.mathworks.nl/help/matlab/ref/textscan.html#inputarg_formatSpec
Now you can read your text file by calling:
C = textscan(FID,formatSpec);
Which stores each column in a cell in C. So the first column is C{1}, the second C{2}, etc.
Finally make sure you close your file by using the file id:
fclose(FID);
Good luck!