Get old-style help in Matlab's command window - matlab

Short version of question
In recent versions of Matlab (I have seen it in R2014b and R2015a on Windows), when you type help foo you get a brief description of the function and its signatures. For example, typing help bsxfun produces something like this (only with better format):
This MATLAB function applies the element-by-element binary operation specified by the function handle fun to arrays A and B, with singleton expansion enabled.
C = bsxfun(fun,A,B)
Reference page for bsxfun
See also arrayfun, repmat
Other uses of bsxfun
distcomp/bsxfun
This is of course only a summary of the actual documentation. To get the full documentation you need to type doc foo. This opens the HTML help browser, which takes quite some time (at least on some computers).
Is there a way to get the full help in the command window (thus avoiding the help browser), as it used to be in older Matlab versions?
Long version of question
To look into this in more detail, I'll define "old" Matlab versions as those that don't have HTML help, and "new" versions as those that do. I also need to give each type of help a name, in order to refer to them:
FP (Full, Plain): full help in the form of plain text, shown in Matlab command window (old style).
SH (Summarized, HTML): summarized help in the form of HTML, shown in Matlab command window.
FH (Full, HTML): full help in the form of HTML, shown in the help browser.
As is well known, the text for FP help is contained in the first comment lines in the file defining the function. In new Matlab versions, functions may also have an associated HTML file. This file contains SH help in an HTML tag, and FH help in HTML code.
Possible behaviour is:
In old Matlab versions, help foo produced FP help.
In new Matlab versions, help foo produces SH help if foo has an associated HTML help file, and FP help if it doesn't.
In new Matlab versions, doc foo produces FH help if foo has an associated HTML help file. If it doesn't, FP help is shown in the help browser (without format).
So the problem is more properly phrased as: how to show FP help in new Matlab versions when foo has an associated HTML help file. The question is meaningful because
Most Matlab functions do have an associated HTML help file.
Most Matlab functions, even built-in functions (that have no m-code), have and m-file containing FP help.
An additional motivation is that in some cases the FP documentation contains features that don't appear in the FH documentation (see for example here).

Original answer (Matlab versions R2014b, R2015a)
Although the documentation doesn't tell, the help function in these Matlab versions supports zero, one or two output arguments. You can check this typing open help and looking at the function signature:
function [out, docTopic] = help(varargin)
In essence, help works internally as follows:
It creates an object called process, of class helpUtils.helpProcess, by calling the class constructor as:
process = helpUtils.helpProcess(nargout, nargin, varargin);
where nargout, argin and varargin are those with which help was called.
It runs the method process.getHelpText, which calls the undocumented, built-in function helpfunc, and as a result sets the property process.helpStr. This property contains the help string which is shown in the command window.
As it turns out, at least on Windows, depending on the value of nargout (which gets passed to the constructor helpUtils.helpProcess) the resulting help string will be FP or SH. Namely, it will be FP if nargout>0, and SH if nargout==0. You can check this by typing the following code (adapted from help.m) directly in the command window:
process = helpUtils.helpProcess(1, 1, {'bsxfun'});
process.getHelpText
process.helpStr
This will produce FP help. On the other hand, changing the first 1 (which corresponds to nargout in the actual call) into a 0,
process = helpUtils.helpProcess(0, 1, {'bsxfun'});
process.getHelpText
process.helpStr
will produce SH help.
I don't know why this is so, that is, how it works on a deeper level than this. All I know is that the getHelp method calls the undocumented helpfunc, which is at least involved in producing FP help.
So, to get FP help you need to call help with one or two output arguments. For example,
str = help('foo')
assigns the FP help text to variable str and displays it. Or you can use
disp(help('foo'))
which also has the effect of calling help with an (implicit) output argument.
To have this behaviour from the standard command help foo, you could define a help function to override Matlab's help, and place it in your Matlab document folder. This folder normally appears first in the path (or you can make sure it does by editing startup.m), and thus has precedence. The new function will essentially call Matlab's help with one output argument, and then display the resulting (FP) help text. In order to call the overriden function it is necessary to temporarily change to its folder:
function help(varargin)
if isempty(varargin)
varargin = {'help'}; %// `help` should be equivalent to `help help`
end
d = pwd; %// take note of current folder
cd(fullfile(matlabroot, 'toolbox', 'matlab', 'helptools')) %// folder where the
%// standard `help` function is
disp(help(varargin{1}));
cd(d) %// restore folder
So now, finally, help foo produces the old-style (FP) help.
Edit for Matlab version R2015b
In Matlab R2015b the behaviour seems to have changed for the better. Typing help foo no longer produces SH help. It's not exactly FP either. In fact it's better than that: it produces FH help but in the command Window, not in the browser. Or, equivalently, it produces FP help but with links and better formattting.
So no need to tweak anymore!
Edit for Matlab version R2018a
Matlab R2018a again gives SH help. The solution provided in this answer works (that is, produces FP help).
So back to tweaking!

A better way is to include the full path to the function when using the help command, then old style full help is displayed and the links also work, e.g. try:
help surf
help(fullfile(matlabroot, 'toolbox', 'matlab', 'graph3d', 'surf.m'))
I’ve just submitted an override help function based on this to MATLAB FEX:Full Command Line Help

Related

MatLab - dicm2nii - Custom output filenames (.json, .gz)

converting dicm to nii works great with the help of this script from xiangruili :
https://github.com/xiangruili/dicm2nii/blob/master/dicm2nii.m
BUT I need to modify the output filenames and add a string to it. The function save_json of the script (dicm2nii.m) was promising, but I am new to matlab and have the feeling that there is a simple solution to this problem.
Cant somebody help me, please!
Thanks!
As #Wolfie correctly mentioned, this is not something easily addressed for people unfamiliar with the particular program. But I took a very quick look since I currently use other tools for DICOM to NiFTI conversion and was curious about this one. Here are some general comments that hopefully will help.
The "json" file is just for metadata, and you probably care more about the .nii image file (or both). It looks like nii_tool('save', nii, filename, force_3D) handles the latter.
The nii_tool and save_json calls are just passed a variable containing the output filename, which you could create/modify using any of the standard MATLAB methods (e.g., sprintf or strcat). There are already some examples of this within the code in the calls to nii_tool('save', ...).
Since you say that you are new to MATLAB, it is probably easiest for you (and likely everyone) to write a script to rename the files after exportation. That way, you don't have to worry about catching all of the cases/ instances within the 3000 lines of code that someone else wrote and just fix it with a simple program at the other end. Becomes a much more tractable problem that way.
As an aside, I currently use dcm2niix ( available from GitHub or NITRC) for this conversion outside of MATLAB.

How to automatically convert a Matlab script into a Matlab function?

My problem is the following:
I have very many (~1000) mutually calling Matlab scripts, which are very poorly written, regularly damage each other's environments and generally became unmanageable.
One of the reasons I even got this problem is that I need to write a testsuite covering a big part of them. Luckily, for most of them the main criterion of 'correctness' is 'they don't crash'.
Just running them one by one in a loop is generally not an option, because they regularly call clear classes, close all, clc, shadow built-in functions and operators, et cetera.
So my original aim was to find a way to run a matlab script in sort of an 'isolated environment', but I didn't find a good way to do it. (Suggestions welcome, but it is not the main question.)
Since I will need to convert them all to functions anyway, I am looking for some way to do it auto-magically, or at least semi-automatically.
What I can mean semi-automatically:
Just add a line function varargout = $filename( varargin ) as the first line of the file, and end as the last one. This will at least make them runnable as functions with feval and all such functions and (more importantly) prevent them from damaging the test-runner.
Do point 1 and scan the file for referencing undeclared variables and add them as function arguments. This should be also doable, since the names of the variables are known. This will not help identifying output variables, but will still be a lot of help. For example, we could pack the whole workspace into one big output structure.
Do a runtime version of point 2. This way the 'magical converter' can actually track execution environments (workspaces) and identify which variables are implicitly used as 'input arguments' of a script, and which would be later used 'output arguments'. This option looks EXPHARD, but for a small number of calls should be not too bad in practice.
Point 1 I can implement myself using sed, as I also can get rid of all clear classes and clc, but the options 2 and 3 seem much harder. Is there anything at least remotely resembling options 2 or 3?

How to document a function in Octave?

The publish function in MATLAB works for both scripts and functions,
while the one for Octave works only for scripts: if I enter
publish myFunc.m
Octave gave
error: publish: Only Octave script files can be published.
Am I able to publish a function in Octave? If yes, how?
You can use Octave Forge generate_html package which is meant to generate html of individual functions. It is mostly used to generate the documentation of Octave Forge packages, and its defaults reflect that, but you could add any style you want.
This package will use the same help text that the help function in Octave sees which is the first block of comments in the file that does not start by Copyright or Author. You can have it in plain text but for nicer formatting, you can use Texinfo. In that case, the first line of the help text should be -*- texinfo -*-. There is a page on the Octave wiki with tips on how to write nice help text including a short section on Texinfo syntax (the actual Texinfo manual can be a bit overwhelming).
In addition to the help text, the generate_html package also identifies %!demo blocks and generates a section with the demo code and output it generates, including figures.
The best way to see how help text and demo blocks work in Octave is to check the source (as #Andy pointed out in the comments). For example, see the source for inpolygon (scroll to the bottom to find the %!demo blocks, right before %!test and %!error). The generate_html package generates this page (note the Demonstration blocks).
This is a "multiple questions in one" question, making lots of assumptions in between, so let's address those first:
1. I'll start by the question in the comment, since that's the easiest: Matlab's publisher is not a code documentation tool. It's a "make a quick report that includes both text and code to show at your supervisor meeting or write a quick point in a blog" tool. So the link you point to is simply irrelevant in this case, since that talks about documentation for matlab code.
2. The fact that matlab's publisher also "works for functions", particularly given the first point here, should be considered to be more of a bug than a feature, or at most as a trivial undocumented extension. If you look at the matlab documentation for the publish command, you'll see it expects a filename, not a function with arguments, and the documentation only talks about scripts and makes no mention of 'function' compatibility.
3. Furthermore, even if you did want to use publisher as a "documentation tool", this is counterintuitive for functions in this format, since you need to provide arguments in order for publisher to work (which will not be shown in the actual report), you'll need a modified version that displays intermediate calculations (as opposed to your normal version which presumably does not), and the function just spews an ugly ans= blabla at the end of the report. If your end goal is documentation, it might be best to write a bespoke script for this anyway, showing proper usage and examples, like matlab does in its actual documentation.
Having said all that, yes, there is a 'cheat' you can do to include a function's code in your published report, which is that, in octave (also matlab since R2016b), functions can be defined locally. A .m file that only contains function definitions is interpreted as a function file, but if there are other non-function-declaration instructions preceding the function definitions (other than comments), then it is seen as a script. So if you publish this script, you effectively get a published report with function code in it:
%% Adding function
% This function takes an input and adds 5 to it.
%% Example inputs
In = 10;
%% The function itself
% Marvel at its beauty!
function Out = myfun(In)
%% Here is where the addition takes place.
% It is a beautiful addition
Out = In + 5;
end
%% Example use
Out = myfun(In)
(If you're not happy about having to create a 'wrapper script' manually, you can always create your own wrapper function that does this automatically).
However, both the matlab and octave publishers are limited tools by design. Like I said earlier, it's more of a "quick report to show numbers and plots to your supervisor" tool, rather than a "make nice documentation or professional reports" tool. Instead, I would invest in a nice automated latex workflow, and have a look at code formatting tools for displaying code, and simply wrap that code in a script that produces output to a file that you can then import into latex. It may sound like more work, but it's a lot more flexible and robust in the long term, particularly since the formatting commands can be very quirky as well as limited.

Can the MATLAB editor show the file from which text is displayed? [duplicate]

In MATLAB, how do you tell where in the code a variable is getting output?
I have about 10K lines of MATLAB code with about 4 people working on it. Somewhere, someone has dumped a variable in a MATLAB script in the typical way:
foo
Unfortunately, I do not know what variable is getting output. And the output is cluttering out other more important outputs.
Any ideas?
p.s. Anyone ever try overwriting Standard.out? Since MATLAB and Java integration is so tight, would that work? A trick I've used in Java when faced with this problem is to replace Standard.out with my own version.
Ooh, I hate this too. I wish Matlab had a "dbstop if display" to stop on exactly this.
The mlint traversal from weiyin is a good idea. Mlint can't see dynamic code, though, such as arguments to eval() or string-valued figure handle callbacks. I've run in to output like this in callbacks like this, where update_table() returns something in some conditions.
uicontrol('Style','pushbutton', 'Callback','update_table')
You can "duck-punch" a method in to built-in types to give you a hook for dbstop. In a directory on your Matlab path, create a new directory named "#double", and make a #double/display.m file like this.
function display(varargin)
builtin('display', varargin{:});
Then you can do
dbstop in double/display at 2
and run your code. Now you'll be dropped in to the debugger whenever display is implicitly called by the omitted semicolon, including from dynamic code. Doing it for #double seems to cover char and cells as well. If it's a different type being displayed, you may have to experiment.
You could probably override the built-in disp() the same way. I think this would be analagous to a custom replacement for Java's System.out stream.
Needless to say, adding methods to built-in types is nonstandard, unsupported, very error-prone, and something to be very wary of outside a debugging session.
This is a typical pattern that mLint will help you find:
So, look on the right hand side of the editor for the orange lines. This will help you find not only this optimization, but many, many more. Notice also that your variable name is highlighted.
If you have a line such as:
foo = 2
and there is no ";" on the end, then the output will be dumped to the screen with the variable name appearing first:
foo =
2
In this case, you should search the file for the string "foo =" and find the line missing a ";".
If you are seeing output with no variable name appearing, then the output is probably being dumped to the screen using either the DISP or FPRINTF function. Searching the file for "disp" or "fprintf" should help you find where the data is being displayed.
If you are seeing output with the variable name "ans" appearing, this is a case when a computation is being done, not being put in a variable, and is missing a ';' at the end of the line, such as:
size(foo)
In general, this is a bad practice for displaying what's going on in the code, since (as you have found out) it can be hard to find where these have been placed in a large piece of code. In this case, the easiest way to find the offending line is to use MLINT, as other answers have suggested.
I like the idea of "dbstop if display", however this is not a dbstop option that i know of.
If all else fails, there is still hope. Mlint is a good idea, but if there are many thousands of lines and many functions, then you may never find the offender. Worse, if this code has been sloppily written, there will be zillions of mlint flags that appear. How will you narrow it down?
A solution is to display your way there. I would overload the display function. Only temporarily, but this will work. If the output is being dumped to the command line as
ans =
stuff
or as
foo =
stuff
Then it has been written out with display. If it is coming out as just
stuff
then disp is the culprit. Why does it matter? Overload the offender. Create a new directory in some directory that is on top of your MATLAB search path, called #double (assuming that the output is a double variable. If it is character, then you will need an #char directory.) Do NOT put the #double directory itself on the MATLAB search path, just put it in some directory that is on your path.
Inside this directory, put a new m-file called disp.m or display.m, depending upon your determination of what has done the command line output. The contents of the m-file will be a call to the function builtin, which will allow you to then call the builtin version of disp or display on the input.
Now, set a debugging point inside the new function. Every time output is generated to the screen, this function will be called. If there are multiple events, you may need to use the debugger to allow processing to proceed until the offender has been trapped. Eventually, this process will trap the offensive line. Remember, you are in the debugger! Use the debugger to determine which function called disp, and where. You can step out of disp or display, or just look at the contents of dbstack to see what has happened.
When all is done and the problem repaired, delete this extra directory, and the disp/display function you put in it.
You could run mlint as a function and interpret the results.
>> I = mlint('filename','-struct');
>> isErrorMessage = arrayfun(#(S)strcmp(S.message,...
'Terminate statement with semicolon to suppress output (in functions).'),I);
>>I(isErrorMessage ).line
This will only find missing semicolons in that single file. So this would have to be run on a list of files (functions) that are called from some main function.
If you wanted to find calls to disp() or fprintf() you would need to read in the text of the file and use regular expresions to find the calls.
Note: If you are using a script instead of a function you will need to change the above message to read: 'Terminate statement with semicolon to suppress output (in scripts).'
Andrew Janke's overloading is a very useful tip
the only other thing is instead of using dbstop I find the following works better, for the simple reason that putting a stop in display.m will cause execution to pause, every time display.m is called, even if nothing is written.
This way, the stop will only be triggered when display is called to write a non null string, and you won't have to step through a potentially very large number of useless display calls
function display(varargin)
builtin('display', varargin{:});
if isempty(varargin{1})==0
keyboard
end
A foolproof way of locating such things is to iteratively step through the code in the debugger observing the output. This would proceed as follows:
Add a break point at the first line of the highest level script/function which produces the undesired output. Run the function/script.
step over the lines (not stepping in) until you see the undesired output.
When you find the line/function which produces the output, either fix it, if it's in this file, or open the subfunction/script which is producing the output. Remove the break point from the higher level function, and put a break point in the first line of the lower-level function. Repeat from step 1 until the line producing the output is located.
Although a pain, you will find the line relatively quickly this way unless you have huge functions/scripts, which is bad practice anyway. If the scripts are like this you could use a sort of partitioning approach to locate the line in the function in a similar manner. This would involve putting a break point at the start, then one half way though and noting which half of the function produces the output, then halving again and so on until the line is located.
I had this problem with much smaller code and it's a bugger, so even though the OP found their solution, I'll post a small cheat I learned.
1) In the Matlab command prompt, turn on 'more'.
more on
2) Resize the prompt-y/terminal-y part of the window to a mere line of text in height.
3) Run the code. It will stop wherever it needed to print, as there isn't the space to print it ( more is blocking on a [space] or [down] press ).
4) Press [ctrl]-[C] to kill your program at the spot where it couldn't print.
5) Return your prompt-y area to normal size. Starting at the top of trace, click on the clickable bits in the red text. These are your potential culprits. (Of course, you may need to have pressed [down], etc, to pass parts where the code was actually intended to print things.)
You'll need to traverse all your m-files (probably using a recursive function, or unix('find -type f -iname *.m') ). Call mlint on each filename:
r = mlint(filename);
r will be a (possibly empty) structure with a message field. Look for the message that starts with "Terminate statement with semicolon to suppress output".

Use of %# notation for declaring dependencies

In MATLAB, you can declare a function dependency with:
%#function myExtraFunctionName
Doing so tells MATLAB that myExtraFunctionName is required by the script or function to operate, even if it's called by an eval statement or some other method that the various dependency checkers or compilers can't figure out.
I have several files that load in .mat or other data files that are required for the script to run, and I would like to include them in a similar manner so that when I run a dependency check with, say fList = matlab.codetools.requiredFilesAndProducts, it will find these data files as well. Ultimately what I would like to be able to do is generate the list of files and pass it to zip to archive every file required to run a given script or function, including data files.
Trying to find any documentation on this feature is challenging because the MATLAB help won't let you just type in %# and searching for %#function just searches for function. Google does the same thing: "hash percent function" returns lots of information on hash tables, "%#function matlab" strips out the important characters, and "declare matlab function" "declare matlab function dependency" turns up nothing useful. I don't remember where I encountered this syntax, so I don't even know if this is a documented feature or not.
I have two questions:
Can someone point me to documentation on this syntax along with some clues as to what keywords I should be using to search?
Can this be used to declare dependencies other than m-files and, if not, how can I go about doing that?
%#function is a pragma directive that informs MATLAB Compiler that the specified function will be called indirectly using feval, eval, or the like.
This is important because the static code analyzer will not be able to detect such dependencies on its own. For instance the name of the function could be stored in a string as in:
fcn = 'myFunction';
feval(fcn)
As far as I know, this is only used by the MATLAB Compiler, nothing else.
There are other similar pragmas. For example MATLAB Coder has %#codegen compiler directive.
I don't have any answer, but maybe you can use this website:
http://www.symbolhound.com/
It let you do search using symbols.