Dmitri Nesteruk
Dmitri Nesteruk

Reputation: 23799

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?

Upvotes: 7

Views: 3302

Answers (2)

RTL
RTL

Reputation: 3587

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:

enter image description here

Upvotes: 3

Amro
Amro

Reputation: 124563

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:

published_html

You could wrap that last code in a helper function render_latex_string(str) and call it from different places.

Upvotes: 8

Related Questions