How to document object-oriented MATLAB code? [closed] - matlab

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'm writing a sizable application using object-oriented MATLAB, and this has gotten me thinking about how to document the code. If this was C, I would use Doxygen. For Java, I'd use JavaDoc. Both have mostly agreed-upon standards for how class and method documentation should look and what it should contain.
But what about MATLAB code? The most I've seen in TMW's own classes is a short sentence or two at the top of the class, and I can't find any topics devoted to documenting sizable MATLAB applications.
So how do you document your MATLAB classes? Any particular style issues or additional tools?

I realize the question is stale, but for the benefit of Google: Matlab has a built-in feature for that. You write your comments in a certain style (a la JavaDoc) and they get picked up by the help and doc functions. It can be used to document classes, properties, and methods. It is surprisingly complete, yet a little finicky. The doc is here:
http://www.mathworks.com/help/matlab/creating-help.html

I document my oo code the following way:
At the beginning of the file that contains 'classdef', I write a summary of what the class does, and typical usage. I also explain properties in detail and I add a 1-sentence description of each method.
After each property definition, I add one explanatory sentence about it (on the same line)
Each method is documented like a function, i.e. it has a H1-line, a synopsis, and an explanation of the input and output parameters.
When you call 'doc myClass', you will see (1) at the beginning, followed by the list of properties explained by the sentences you added in (2) and the list of methods that show the H1-line and the rest of the help (3) if you click on the link.
In addition, all my classes subclass a general superclass which implements (among others) the method 'help' that calls doc(class(obj)), which allows me to bring up the help from every instance of the class.
Example
%# MYCLASS is a sample class
%# All this text will show up at the top of the help if you call 'doc myClassName'
%#
%# myClass is an example for documentation. It implements the following properties and methods:
%# PROPERTIES
%# myProp - empty sample property (some more explanation could follow here)
%#
%# METHODS
%# myMethod - sample method that calls doc
%#
classdef myClass
properties
myProp = []; %# empty sample property
end %# properties
methods
%%# MYMETHOD -- use %% so that you can easily navigate your class file
function myMethod(obj)
%#MYMETHOD calls up the help for the object
%#
%# SYNOPSIS myMethod(obj)
%# INPUT obj: the object
%# OUTPUT none
%#
try
doc(class(obj))
catch
help(class(obj))
end
end %#myMethod
end %#methods
end %#myClass
Edit 1 If you want a nice html documentation, you can, in addition, use m2html to generate it for you. M2html will collect the help texts and it can even do dependency graphs.
Edit 2 While m2html documents standard Matlab code nicely, it has no specific support for classes. This means that you get the methods as 'subfunctions' linked in the class, but you do not get as nice a summary as you'd get with Doxygen, or which you get with the built-in documentation browser.

Try Sphinx with the matlabdomain extension. Sphinx is a Python package that auto-documents code using ReStructuredText (rst) markup. The extension sphinxcontrib-matlabdomain allows auto-documentation of MATLAB code that uses rst markup recognized by Sphinx in its docstrings. Send bugs and suggestions to the issue tracker on BitBucket.
For example, the following code in my_project/my_fun.m:
function [outputs] = my_fun(args)
% MY_FUN does really cool stuff
% [OUTPUTS] = MY_FUN(ARGS)
%
% :param args: Input arguments
% :type args: cell array
% :returns: outputs
% :raises: :exc:`my_project.InvalidInput`
code ...
end
would be documented in an rst file like this:
.. _my-project
My Project
==========
.. automodule:: my_project
This folder contains all the functions and classes for my project.
My Function
-----------
.. autofunction:: my_fun
and would produce html (or pdf, latex, and many others) like what is shown on this blog post.

There exists a Doxygen-Adapter for M-Files on FileExchange, see http://www.mathworks.com/matlabcentral/fileexchange/25925-using-doxygen-with-matlab.

Related

Calling functions from inside (Matlab) code sections [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a massive script consisting of many code sections that I run independently of each other. For some of these code sections, there is a lot of repeating code, and so I wanted to define a function that I can call multiple times from a given code section. However, I am either getting the error "Function definitions are not permitted in this context.", or, once the code execution reaches the function call, it says the function is not defined.
So it seems that Matlab (2016b) does not accept functions to be defined within code sections, or I am doing something else that's wrong.
What I tried:
define the entire script as a function, named exactly as the name of the containing .m file, and with a corresponding 'end' on the very last line
define the function containing my repeating code either at the end of the code section for which it is relevant
.. or at the end of the file (before the top-most function's own 'end')
.. or at the end of the file (after the top-most function's own 'end')
My code organisation might be criticised, e.g. I might instead use multiple functions in my file, rather than script-style code sections. However, I would like to know whether there is a way to be able to call functions from inside code sections.
You need to read the following documentation:
Scripts and functions
Create functions in files
Notably, the second contains the relevant information:
Starting in R2016b, another option for storing functions is to include them at the end of a script file.
You say you're using R2016b, so you can define functions within scripts, but they must be at the end of the file. The documentation contains the following example of a valid script containing functions:
x = 3;
y = 2;
z = perm(x,y)
function p = perm(n,r)
p = fact(n)*fact(n-r);
end
function f = fact(n)
f = prod(1:n);
end

Understanding eclipse's TPTP profiling tool trace format

I'm new to eclipse's TPTP profiling tool . I have received a TPTP trace and I need help to understand the content provided.
The trace that contains function call entry and exists alongside with parameter of the function call on entry. It is from JHotDraw, a Java program . Here is a sample of the trace:
Entered: CH/ifa/draw/standard/ToolButton.paint---[sun.java2d.SunGraphics2D[font=javax.swing.plaf.FontUIResource[family=Dialog,name=Dialog,style=bold,size=12],color=sun.swing.PrintColorUIResource[r=51,g=51,b=51]]]
Exited: CH/ifa/draw/standard/ToolButton.paint---[sun.java2d.SunGraphics2D[font=javax.swing.plaf.FontUIResource[family=Dialog,name=Dialog,style=bold,size=12],color=sun.swing.PrintColorUIResource[r=51,g=51,b=51]]]
Entered: CH/ifa/draw/application/DrawApplication.paletteUserOver---[CH.ifa.draw.standard.ToolButton[,304,1,24x24,disabled,alignmentX=0.0,alignmentY=0.5,border=javax.swing.border.CompoundBorder#1308786,flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=javax.swing.ImageIcon#1f647e2,disabledIcon=sun.swing.ImageIconUIResource#d253d9,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=javax.swing.ImageIcon#924039,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=javax.swing.ImageIcon#5c7d2e,text=,defaultCapable=false], false]
My questions are:
1)I would like to know why the parameters are sometimes detailed in variable\value pairs (like the PrintColorUIResource object in the first line) and sometimes given as a reference like ImageIcon#924039?
According tot he doc args should output all method arguments.
2) When the parameter is a complex type, how does TPTP describe its content? For example, in the first line, the parameter of the function is an object of type sun.java2d.SunGraphics2D. This object is described by two values, font and color, each of which is recessively defined. From the documentation (link below), I can see the object SunGraphics2D has dozens of local variables, one of which is called font, but none called color. The constructor does have two parameters color and font, but also two other parameters.
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b27/sun/java2d/SunGraphics2D.java
Likewise object sun.swing.PrintColorUIResource at the end of the same function call is described w.r.t. 3 valuse, r,g,b. I can't find these variable in the documentation.
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/sun/swing/PrintColorUIResource.java#PrintColorUIResource
3) Why is the value or the variable name sometimes ommited? eg: maximumSize=,minimumSize=, ... or at the end of the 3rd fct call : =false], false]
4) Is there any documentation I can refer myself to to better understand the trace content?
Thank you for your help and your kind consideration.

How to include a c-header with constants in Matlab Simulink

I'm developing a Simulink modell with many C-s-functions. For an easier handling I want to use constants in the c-s-function as in the simulink-modell. So I have a c-header with preprocesser constants like:
#define THIS_IS_A_CONSANT 10
And there is the question:
How it is possible to include this in Simulink in this way I can use THIS_IS_A_CONSANT for example in a constant source like a workspace-variable?
Thanks and regards
Alex
There is functionality in Simulink that will allow you to include custom C header files that define constants, variables, etc.; however, as far as I know (and as one might expect) this really is only pertinent in cases where code is being generated and compiled.
So, for the most part, this particular functionality is only relevant when you are using Simulink Coder to generate a stand-alone executable from your model. For example, this link shows how to include parameters stored in an external header file during code generation through the use of Simulink.Parameter objects with Custom Storage Classes and the Code Generation - Custom Code Pane under the model's Configuration Parameters.
This link from the Simulink doc shows how to use the #define custom storage class to achieve similar results.
However, it sounds like neither of these really solve your issue, as you want to make use of the code in the header file during simulation.
That said, considering that there are elements in Simulink, such as Stateflow Charts and MATLAB Function blocks, that generate and build code "under the hood" during simulation, it's (at least hypothetically) possible that you might be able to use some of the concepts described above to access the values in your header file from one of those elements during simulation. For example, I was successfully able to access preprocessor macros in a Stateflow chart just by going to the Simulation Target->Custom Code pane under Configuration Parameters and including the text #include "header.h" under Include custom C code in generated: Header file. (In this case, header.h contained the line of C code that you included in your post)
Although it seems like you should be able to extend this functionality further, this really was the limit of what I was able to achieve as far as accessing the header file during simulation was concerned. For example, I know that running a model in Rapid Accelerator mode actually generates and builds code under the hood, so seemingly you should be able to use some combination of the techniques I described above to be able to access values from the header file during simulation. It looks like the code that Rapid Accelerator mode generates doesn't respect all of the settings defined by those techniques in the same way that Simulink/Embedded Coder do, though, so I just kept running into compilation errors. (Although maybe I'm just missing some creative combination of settings that could make that work).
Hopefully that helps explain Simulink's abilities (and limitations) regarding the inclusion of C header files. So to summarize, according to the links included above, what you are asking for is almost barely possible, but in practice... not really.
So if really all you want is to be able to create workspace variables out of the preprocessor #define's in your header file, it probably is just easiest to manually parse the file with a MATLAB script, as had previously been suggested in the comments. Here is a quick-and-dirty script that loads in a header file, iterates over each line, uses a regular expression (which you can improve upon if needed) to parse #define statements, and then calls eval to create variables from the parsed input.
filename = 'header.h';
pattern = '^\s*#define\s*(\w*)\s*(\d*\.?\d+)';
fid = fopen(filename);
tline = fgetl(fid);
while ischar(tline)
tokens = regexp(tline, pattern,'tokens','once');
if(numel(tokens) == 2)
eval([tokens{1} ' = ' tokens{2}]);
end
tline = fgetl(fid);
end
fclose(fid);
You could put this code in a callback so that it will execute every time you load your model. Just goto File->Model Properties->Model Properties, click on the Callbacks tab, and then place the code under whichever callback you desire (such as PreLoadFcn if you want it to run immediately before the model loads).

Accessing variable by string name

I need to load experimental data into scicoslab, a (pretty badly designed) clone fork of scilab which happens to support graphical modeling. The documentation on the web is pretty poor, but it's reasonably similar to scilab and octave.
The data I need to process is contained into a certain number of text files: Data_005, Data_010, …, Data_100. Each of them can be loaded using the -ascii flag for the loadmatfile command.
The problem comes from the fact that loadmatfile("foo", "-ascii") loads the file foo.mat into a variable named foo. In order to to cycle on the data files, I would need to do something like:
for i = [5:5:100]
name = sprintf("Data_%02d", i);
loadmatfile(name, "-ascii");
x = read_var_from_name(name);
do_something(x);
end
where what I search for is a builtin read_var_from_name which would allow me to access the internal symbol table by string.
Do you know if there exist a similar function?
Notes:
There's no way of overriding this behavior if your file is in ascii format;
In this phase I could also use octave (no graphical modelling is involved), although it behaves in the same way.
>> foo = 3.14; name = 'foo'; eval(name)
foo =
3.1400
The above works in MATLAB, and Scilab's documentation says it also has an eval function. Not sure if I understood you correctly, though.
#arne.b has a good answer.
In your case you can also do that in matlab:
a=load('filename.mat')
x=a.('variable_name')
lets go through your points one by one:
"ScicosLab, a (pretty badly designed) clone of Scilab" This in my opinion is an inaccurate way of introducing the software. ScicosLab is not a clone of Scilab but a fork of it. The team behind ScicosLab (INRIA) are the ones who made scocos (now called xcos in Scilab development line). At some point (from Scilab v4) the Scilab team decided to move away from Tcl/tk towards Java, but the SciccosLab/scicos team departed, keep using the language (Tcl) and it's graphical user interface design package (tk). Giving the ScocosLab community the credit that the whole Scilab documentation and support is not very good in general. :) (more about Scilab and the forks here)
Regarding the technical question I'm not sure what you are trying to achieve here, Scilab/ScicosLab still have the eval function which basically does what you want. However this function is to be deprecated in favor of evstr. There is also the execstr function which worth studying.
The loadmatfile, as far as I have understood, "tries" to load the variables defined in a MATLAB .mat file (MATLAB's proprietary tabular format) into the Scilab workspace. For example if there is a variable foo it will "try" to create the variable foo and loads its value from the MATLAB script. Check this example. I would create a variable x(i) = foo in the for loop. again your question is not completely clear.
As a side note maybe you could consider exporting your data as CSV instead of .mat files.

Is there a way to call a subfunction while in cell mode in matlab?

Say I had the following code:
% Cellmode_subfunction_test.m
%% Cell 1
foo(1);
%% Cell 2
foo(2);
%% Definition of the foo subfunction
function foo(num)
disp(['num=' num2str(num)]);
How can test cell 1 and cell 2 with the subfunction defined at the end?
Edit: Basically each of the cells in this example perform some lengthy calculations so I'd like to test and debug them separately. I'm using subfunctions to abstract out and reuse common functionality and since so far this functionality is only used in this particular application I don't really want to place foo in a separate m-file.
Edit(2): I just remembered that I vaguely recall cell mode only working in matlab scripts and not in function m-files and that subfunctions and nested functions are not allowed in such scripts. Thus what I'm asking for is probably not possible.
Although the anonymous function solution given below is perhaps somewhat restrictive as it only allows single expression functions, it did in fact suffice for what I wished to do and hence I've accepted it as a solution to my problem.
CORRECTION:
I misunderstood your use of the word CELL. My apologies. It appears you simply want to define a function at the command line without saving it to a .m file. For this, you can use anonymous functions:
foo = #(num) disp(['num=' num2str(num)]);
Then you can use "foo" as you would any other function.
The way that I normally handle that is by using dbstop somewhere inside of the main function. Then you have access into all of the functions which the main function would normally have access to. If you're working with the ML editor, just use a breakpoint at the first call to foo.
Hope it helps.
Dan