Linking "See also" items in Matlab when publishing using markup - matlab

I wish to publish documentation using Matlab's publish feature. My documentation is in markup format (i.e. contains sections using "%%"), which seems to have the side effect of removing hyperlinks to 'see also' items.
For example, the following header comment will not hyperlink to the knnsearch doc when published:
%% myFunction
% Short description of function.
%
%% Syntax
% myOutput = myFunction(myInput);
%
%% Description
% Longer description of function.
%
% myInput - description of input
% myOutput - description of output
%
%% Example
% myOutput = myFunction('blah');
%
%% See also
% knnsearch
How do I retain 'see also' hyperlinks when using Matlab's publish feature with markup?

I don't think you can do exactly what you're asking for; publishing doesn't automatically add a link to See Also lines, in the same way that doc or help does.
But you can achieve something similar by directly adding a link to your markup:
%% See also
% <matlab:doc('knnsearch') knnsearch>
If you want your function to have the normal functionality of doc or help, and also this functionality, consider including both your normal See Also section, plus a <matlab: > link in something like a "See" rather than "See Also" section.

Related

Execute Example Code in Matlab when Publishing a Function

Background
Matlab has a publish function which outputs a, say, .html file based on the syntax of the comments. Sections which contain example code are indicated by a '%' followed by three spaces. An example function can be seen below, and the .html file generated by the publish function can be seen here.
function randomImage = GenerateRandomImage(n)
%% TestFunction
% generates a random image
%
% randomImage = GenerateRandomImage(n) returns an nxn array of random pixels
%
%% Example
% randomImage = GenerateRandomImage(10);
% figure; imagesc(abs(randomImage));
randomImage = rand(n);
end
Matlab will not automatically evaluate the example code, unless I create a separate script with the example code explicitly uncommitted. An example script is seen below. This time, it automatically includes the outputs of that script, such as the image produced by the example script shown here here.
%% TestFunction
% generates a random image
%
% randomImage = GenerateRandomImage(n) returns an nxn array of random pixels
%
%% Example
randomImage = GenerateRandomImage(10);
figure; imagesc(abs(randomImage));
The Question
Is it possible for the publish function to automatically evaluate the code snippits in the comments of a function and include those outputs in the html file?
The matlab publisher is explicitly meant to be performed on scripts, not function files, since its purpose is to produce a report, where individual sections (marked with %%) become headings, and lines beginning with % immediately under the %% become the description text for that section. Anything that follows after that, both code and comment lines, will be presented by the publisher in a nice little box as the code that was run for that section, and then the results of that code will be shown below that box, but contained within their section.
Putting code in the description text for that section, expecting it to be run is counter-intuitive. In fact, the only reason you might want to put a code snippet in the description is if you wanted to mention some code without running it.
For this reason the publisher provides special syntax (indent by 2 spaces for monotyped text, 3 spaces to add syntax-highlighting to your code).
Publisher is a nice tool, but unfortunately it's fairly limited. The main limitation for me is that you cannot choose which code sections to show results for and which ones not to; it's all or nothing. Therefore I usually resort to a "latex + saved matlab figures + makefile" approach instead for flexible reports. But publisher is nice if you want something quick and dirty; e.g. it's good for keeping a logbook / diary of your work.
Anyway, to answer your question, no, you can't put code in the description and expect it to run. Nor are you expected to 'publish' functions; the fact that a function file responds at all to publishing in the first place is probably more of a side-effect of how publisher gets called more than anything.

mimicking a subsection when publishing

I might be wrong, but as far as I understand Matlab does not have a "subsection" option when publishing.
However, if I go for instance here (-mkdir- documentation), under the Examples section there are three "subsections".
How would you obtain this? If it's through HTML only and not through direct Matlab options, is it possible to assign a shortcut or button to create the HTML fragment?
When publishing to html, you can use html-code:
%%
% <html>
% <h3>subsection</h3>
% </html>
%
This does what I was looking for: it creates a subsection title the same color of the main title.
%%
% <html><h3 style="color:C45400">
% This will produce a Matlab-orange subsection
% </h3></html>
%
%%

How to manually output publishing content from a variable

When using the Publish feature of MATLAB, it typically publishes only what comes after the % signs or the function output. However, is there any command to take a variable and splice its value into text, possibly even creating LaTeX formulae from a MATLAB variable that holds a character string?
Here is an example of rendering LaTeX formulae (one hard-coded in comments, other stored as a string in a variable).
%% LaTeX Examples
% Below are some equations rendered in LaTeX.
% (try to publish this file).
%
%% The definition of e
% Here we use equation embedded in the file.
%
% $$ e = \sum_{k=0}^\infty {1 \over {k!} } $$
%
%% The Laplace transform
% Here we render an equation stored in a variable.
%
% offscreen figure
fig = figure('Menubar','none', 'Color','white', ...
'Units','inches', 'Position',[100 100 6 1.5]);
axis off
str = 'L\{f(t)\} \equiv F(s) = \int_0^\infty\!\!{e^{-st}f(t)dt}';
text(0.5, 0.5, ['$$' str '$$'], 'Interpreter','latex', 'FontSize',28, ...
'HorizontalAlignment','center', 'VerticalAlignment','middle')
snapnow
close(fig);
Here is how it looks like when the file is published as HTML:
You could wrap that last code in a helper function render_latex_string(str) and call it from different places.
To use variables from the workspace
when Publishing to html using disp() with a html encoded string will add the lines to the output (without using the formatting for code output).
for example
str = sprintf('some value: %f from the workspace',variable)
disp(['<html>',str,'</html>'])
Notes:
It is quite sensitive and you may need to add invisible section breaks between
code output and lines produced in this way.
Adding paragraph tags is useful to improve formatting
Sadly (to my knowledge) the publishing markdown interpreter is not used on these lines, they are "injected" into the output, therefore latex equations will not work.
Code
%% HTML option
% This option is anly available with HTML output...
a=1;
str = ['The current value of a is ', num2str(a)];
%%%
%
% When publishing to HTML using the |disp| function with HTML tags
% surrounding the string can allow workspace variables to appear within
% text.
%
% For example the following line is created by evaluating code, it is not a
% comment in the m-file
%
disp(['<html><p>',str,'</p></html>']);
%% Changing the value
% Now if we change a to 2...
a=2,str = ['The new value of a is ', num2str(a)];
%%
% Re-runing a similar code should show the updated value
disp(['<html><p>',str,'</p></html>'])
Output
The code above generates the following:

Is there a way of selectively including code when publishing in Matlab?

I'm writing MATLAB code in order to publish it later. By publishing, I mean the built-in MATLAB publish tool that allows the programmer to make a full report generated from their MATLAB code. There's an option to include the code with this report, section by section, preceding the results of this code. Is there a way to tell MATLAB to include some of this code in the report but not all of it? I know there are quite a few markup code tags, but I wasn't able to find anything on this topic.
Edit: Just to clarify, I want all results to be published, but only some of the code. So simply removing this code is not an option.
Cheers! = )
Hide your code that you don't want people to see in a script. For example, in the "sine_wave" example from the publish documentation page, I added a single line:
junk
Here's the content of junk:
figure()
plot(0:0.01:6,sin(0:0.01:6))
Now run your main script, and the published result has "junk" in the listing, but the contents of junk are not included, and you get the nice version of a sine wave, instead of the crappy one included in their example.
The only way I know of to do this is to remove the code that you don't want to appear in the output. If you just want to display the code and not the output, then you can just set the evalCode property to false in your call to publish.
If you do want the code to be evaluated, and the output to be published as well, then it's just slightly more complicated. You can manually execute the parts of the script that you don't want to publish, then publish the code that you care about (by putting it in it's own .m file). It shouldn't matter if the published code depends on any variables that are initialized in the omitted code, since those variables were added to your workspace when you manually executed the omitted code fragments.
Edit:
Since you've clarified your question to state that you're interested in publishing some of the code, but all of the output, I would think that your best bet is to just modify the "temporary" script (which contains the partial set of code that you wish to publish) to include any fprintf, disp, etc. function calls that you want to have appear in the output.
It's a bit hack-ish, but like I said, I'm not aware of any way to get that kind of fine granularity with "annotations" or using the publish command.
Hope that helps!
Here's a sample script that you can save and publish which will illustrate one workaround. You first have to set the Include code option to false, which stops all evaluated code from appearing, but you can still display code using a syntax highlighted code sample:
%% Controlling what code gets published
% Here's how you can do it...
%% Showing results without code
% If you set the
% <https://www.mathworks.com/help/matlab/matlab_prog/specifying-output-preferences-for-publishing.html#bthbe__-3
% *Include code* option> to |false|, you will see the plot but not the code
% that made it:
surf(peaks); % I'm John Cena!
%% But what if you want some of the code to show?
% The *Include code* setting affects the whole document, so all evaluated
% code will be hidden. If you want some code to show, you can use
% <https://www.mathworks.com/help/matlab/matlab_prog/marking-up-matlab-comments-for-publishing.html#bs_uwzr
% syntax highlighted sample code>. This does mean you have to have duplicate
% sections of code (one is evaluated, one is displayed), but it's the best
% option thus far:
%%
%
% surf(peaks);
%
surf(peaks); % You can't see me, but you see the above!
And here's the published output:
I change the Matlab expression in the publishing options to
myFunction('PUBLISHING');
And the first lines of the function code to check for that input, so I can modify my code to only do certain things when publishing, usually displaying figures etc., but not during normal operation. Or vice versa :)
function [outputs] = myFunction(input1, input2)
isPublishing = (nargin == 1) && strcmp(input1, 'PUBLISHING');
if (nargin == 0) || isPublishing
% Set up default values
input1 = 'Hello';
input2 = 'World';
end
...
end

MATLAB m-file help formatting

I could not find what formatting available to write help for your own MATLAB function. Very little information is available in official documentation.
Do you know about any other formatting that can be visible with Help Browser (not with help function)? As it is for built-in functions. How to format headings (like Syntax, Description, Examples)? Are bullets, tables possible? Or may be it should be a separate file?
I've tried text markup as used for PUBLISH and HTML, didn't work.
I found only one interesting thing. If your function contains mixed case, like testHelpFunction, its name will be highlighted:
No highlighting if it's just testhelpfunction.
Any other thoughts?
UPDATE
Here is extensive documentation I found on creating your own help files:
Providing Your Own Help and Demos
(Dead link replaced with web archive link)
(Dead link removed)
Updated again:
Add Help for Your Program
Display Custom Documentation
Try this other section in the official documentation. It's more thorough. MATLAB > User's Guide > Desktop Tools and Development Environment > Customizing Help and Demos > Providing Your Own Help and Demos. This describes both simple helptext and generating separate HTML help files.
Here's the helptext formatting I've picked up on and found useful.
function foo(x,y,z)
%FOO One-line description goes here
%
% foo(x,y,z)
%
% Multi-line paragraphs of descriptive text go here. It's fine for them to
% span lines. It's treated as preformatted text; help() and doc() will not
% re-wrap lines. In the editor, you can highlight paragraphs, right-click,
% and choose "Wrap selected comments" to re-flow the text.
%
% More detailed help is in the extended help.
% It's broken out like this so you can keep the main "help foo" text on
% a single screen, and then break out obscure parts to separate sections.
%
% Examples:
% foo(1,2,3)
%
% See also:
% BAR
% SOMECLASS/SOMEMETHOD
disp(x+y+z);
function extended_help
%EXTENDED_HELP Some additional technical details and examples
%
% Here is where you would put additional examples, technical discussions,
% documentation on obscure features and options, and so on.
error('This is a placeholder function just for helptext');
The first line after the function signature is called the "H1 line". It needs to be just one line so it is properly picked up by contentsrpt(), which can autogenerate a Contents.m file from the helptext in your functions
The function name in the H1 line is all caps, regardless of actual capitalization of the function name in the signature
Case matters for the "See also". I'm not sure which all cases work; this one does for sure.
Function names after "See also:" are all caps. Method names are qualified; I think names of methods in the same class as the current method can be unqualified.
Everything between the H1 line and "Examples:" is just a conventional formatting that I find readable; help() doesn't treat it specially.
You can use a limited form of hyperlinks in help. In particular, you can use hyperlinks to invoke arbitrary Matlab commands, and point to other sections of helptext by having it invoke help(). You can use this to point to any function; "function>subfunction" is just the syntax for addressing subfunctions in help() calls. Unfortunately, since you need to put either "help" or "doc" in those hyperlinks, it only works in one or the other presentation form. It would be nicer if there were a direct helptext hyperlink form.
I think the most important aspect in help formatting is that there is a help at all, and that your formatting is consistent, so that you (and people working with you) don't waste time finding out how to look for the information. Note that for OOP, it is useful to have a superclass with a 'help'-method that calls doc(class(obj)), since you cannot easily access the help from an instantiation of your class
To help me be consistent (and to make sure I don't forget stuff), I have created an automatic function template on the file exchange.
Here's the minimal header
function testhelp
%TESTHELP is an example (this is the H1 line)
%
% SYNOPSIS: a=testhelp(b,c)
%
% INPUT b: some input parameter
% c: (opt) some optional input parameter. Default: []
%
% OUTPUT a: some output parameter
%
% REMARKS This is just an example, it won't run
%
% SEE ALSO testHelpFunction
%
% created with MATLAB ver.: 7.11.0.584 (R2010b) on Mac OS X Version: 10.6.4 Build: 10F569
%
% created by: Jonas
% DATE: 01-Oct-2010
%
I figure there is some (see example), but I've never found the appropriate documentation. I often have such blocks:
% ...
%
% See also:
% this_other_function()
%
% <author>
And the See also part is formatted as a title, but if you replace See also by something else, it doesn't work. If anyone finds the list of such supported titles, please link to it here!
EDIT:
I've recently come to learn about matlab's built-in publishing system. It seems MATLAB comments support some form of markup not so far from Markdown's syntax (as used on SO itself), with support for LaTeX equations and all.
There's a post by "Loren on the art of MATLAB" with a short introduction on publishing and markup. For a full reference, see Making Up MATLAB Comments for Publishing on the Mathworks website.
When your code is ready, you can export the result to HTML/PDF/XML, etc. using the publish() function. I use the following snippet to export my files:
% Other formats are supported, refer to documentation.
options.format = 'html';
% I don't evaluate the code, especially for functions that require arguments.
% However, if providing a demo, turning this on is a fantastic way to embed
% figures in the resulting document.
options.evalCode = false;
% You can run this in a loop over files in the currrent directory if desired.
publish('script.m', options);