Text and Plots in Matlab to LaTeX - matlab

I like to create a "report generation" script in Matlab.
Suppose we have a Matlab array, data and we want to export the following to a .tex file:
"The information in the first element of data is X." This would be followed by a plot of X.
I have already tried help latex in Matlab and aware of the various packages on Matlab file exchange. However I have seen nothing so far that will allow me to export both text and plots in the same Matlab script to a .tex file.

The publish function may work for you.
Create this script, foo.m:
%%
% The information in the first element of data is X.
plot(X)
And publish it to LaTeX:
>> publish foo latex

You might want to take a look at this article published in TUGboat (the official magazine of the TeX Users Group):
http://www.tug.org/TUGboat/Articles/tb24-2/tb77seta.pdf
Generating LaTeX documents through Matlab (S. E. Talole and S. B. Phadke)
Good luck!

Are you aware of matlab2tikz? i've used it extensively for my PhD-Thesis, albeit only for exporting single plots. But I guess it should be easily possible to whip something up that combines the power of MATLABs LaTeX export capabilities.

Exporting figures from Matlab to a .tex file is just a matter of exporting the figure to an appropriate format and then including the figure file in the .tex file. Would something like the code listed below work for your needs?
Using LaTeX to generate dvi:
% Include code to write text to .tex file (fid is assumed to be the file id of the .tex file)
print(gcf,'figure1','-depsc','-r100');
fprintf(fid,'\includegraphics[width=4in]{figure1.eps}\n');
Using pdfTeX to generate pdf:
% Include code to write text to .tex file (fid is assumed to be the file id of the .tex file)
print(gcf,'figure1','-djpg','-r100');
fprintf(fid,'\\includegraphics[width=4in]{figure1.jpg}\n');

Related

detect whether .m file is matlab or mathematica

I have been editing Matlab script in Vim for some time now. Recently I started taking an interest in moving my Mathematica work to plain text files so they can be managed using git and edited using Vim. Unfortunately Mathematica also uses the .m extension for its package files and is therefore not easily distinguished from Matlab scripts. Since I would like my editor to do the work for me I was wondering if anyone has come up with an idea for identifying both based on the contents of the file. I would be fine with something that works in most cases, but am reluctant to use a solution that requires alterations in the scripts such as adding a comment.
A ".mat" or ".m" file created with MATLAB's save() function will always start with the plain text identifier "MATLAB". So, using MATLAB syntax, you might do this:
% Set up a workspace variable and save to file
tmp = 1:10;
save('test.m');
% Open the file, read the first line and close again
fid=fopen('test.m');
firstline=fgetl(fid);
fclose(fid);
% Branch depending on file format
if ((numel(firstline) >= 6) && strcmp(firstline(1:6), 'MATLAB'))
disp('This may well be a MATLAB file.');
else
disp('This is probably not a MATLAB file.');
end

Create Matlab figures in LaTeX using matlabfrag or alternatives

I want to include Matlab figures into latex preferably with vectorised formats but with LaTeX MATLAB fonts for all text. I have been using the MATLAB function matlab2tikz which worked perfect for simple figures, but now my figures have too many data points which cause an error. So matlab2tikz is not suitable.
I've been looking at matlabfrag which I think will accomplish what I want, but when I run the script in LaTeX as detailed by the user guide it has an error File not found.
This is my code:
\documentclass{article}
\usepackage{pstool}
\begin{document}
\psfragfig{FileName}
\end{document}
Where FileName is the name of the .eps and .tex that matlabfrag creates. Has anyone come across this problem? Or recommend any other functions/methods to use?
I'm using Texmaker on Windows 7.
My advice would be to rethink your workflow.
Instead of reusing your Matlab code to plot figures and be dissappointed by ever changing outputs with matlab2tikz, start reusing your latex code to plot figures and don't bother about plotting in Matlab anymore (at least not for beautiful plots).
matlab2tikz is just generating latex code based on the latex-package pgfplots. To understand the working of this package is pretty easy, as it is intended to be similar to Matlab.
So why bother and always let matlab2tikz do the work for you? Because again and again you won't be entirely happy with the results. Just try to write the pgfplots-code from scratch and just load the data from Matlab.
Here is a convenient function I wrote to create latex-ready text files:
function output = saveData( filename, header, varargin )
in = varargin;
numCols = numel(in);
if all(cellfun(#isvector, in))
maxLength = max(cellfun(#numel, in));
output = cell2mat(cellfun(#(x) [x(:); NaN(maxLength - numel(x) + 1,1)],in,'uni',0));
fid = fopen(filename, 'w');
fprintf(fid, [repmat('%s\t',1,numCols),'\r\n'], header{:});
fclose(fid);
dlmwrite(filename,output,'-append','delimiter','\t','precision','%.6f','newline', 'pc');
else
disp('saveData: only vector inputs allowed')
end
end
Which could for example look like the following, in case of a bode diagram:
w G0_mag G0_phase GF_mag GF_phase
10.000000 40.865743 -169.818991 0.077716 -0.092491
10.309866 40.345290 -169.511901 0.082456 -0.101188
10.629333 39.825421 -169.196073 0.087474 -0.110690
10.958700 39.306171 -168.871307 0.092787 -0.121071
11.298273 38.787575 -168.537404 0.098411 -0.132411
In your tikzpicture you can then just load that file by
\pgfplotstableread[skip first n=1]{mydata.txt}\mydata
and store the table into the variable \mydata.
Now check pfgplots how to plot your data. You will find the basic plot command \addplot
\addplot table [x expr= \thisrowno{0}, y expr= \thisrowno{3} ] from \mydata;
where you directly access the columns of your text file by \thisrowno{0} (confusing, I know).
Regarding your problem with to many data points: pgfplots offers the key each nth point={ ... } to speed things up. But I'd rather filter/decimate the data already in Matlab.
The other way around is also possible, if you have to few data points the key smooth smoothes things up.

Writing matlab vector to a file that is matlab readable

For matlab: Is there a way to write the value of a vector to a file that can later be opened and read by another matlab program?
Specifically: I have a matlab program that computes a binary-valued vector $zvector$ with 10^7 entries. I want to write $zvector$ as data to an output file so that it can be emailed and easily read as input to another matlab program. Ideally, the output file would be called “Output.m” and would look like:
zvector=[
0
1
1
…
0
1
];
I like the .m format because it is easy to use for matlab input. I have experimented with matlab’s write() and fwrite() commands, with no success. I observe that these generate files that cannot be easily read as matlab-recognizable inputs (at least, I do not know how to read from them). Is there a way to accomplish my goals? Thanks.
PS: I am interested in the easiest way. If this involves a different type of file format (not a .m format) that is fine. However, in that case, can you provide both the writing and reading commands? Thanks again.
Thanks to #edwinksl for pointing me in the right direction with MAT files. I do not know the accepted practice here, but in stackexchange math it is encouraged to answer your own question if a hint from comments got you all the way there. So I will answer my own question.
The Mat format does this well. Here are example script files for reading and writing in the Mat format (see also links in above comments for more documentation):
***Script file OutputTest.m:
filename = 'TestFile.mat';
TestVector=[1 1 0 1];
save(filename, 'TestVector');
***Script file IntputTest.m
filename = 'TestFile.mat';
file=load(filename);
z =file.TestVector;
z

Matlab Publish Image PDF

I want to include a picture of my Simulink diagram when I publish my script. I currently print it to an image and manually add it in later.
I read on the Matlab website that I could do this by including a comment <<FILENAME.jpg>> and the publishing tool would pick it up and add it to my report. Unfortunately all this does is add a link to the image, which is not helpful when printing it out.
This is what I have:
print(['-s',simName], '-djpeg', ['html/',simName,'.jpg'])
% <<simName.jpg>>
I've also tried these tips before, but they didn't work for me either.
What you have tried should work. In fact it should work with any JPG file. have you tried what the example from the documentation?
To produce an HTML file containing surfpeaks.jpg from a MATLAB file:
Create a subfolder called html in your current folder.
Create surfpeaks.jpg by running this code in the Command Window.
saveas(surf(peaks),'html/surfpeaks.jpg');
Publish this MATLAB code to HTML.
%% Image Example
% This is a graphic:
%
% <<surfpeaks.jpg>>
%
The alternative is to open the Simulink system with open_system. This will create a snapshot of the model in the published HTML provided the model is closed when the open_system command is issued.
%% Include snapshot of f14 model
%
open_system('f14')
%
If none of these work, then there's something fundamentally wrong with your MATLAB installation, of the way you are using the publish command.
open_system('filename.slx')
make sure the simulink program is in the same folder as the script.

display the output from mat file

Please, any one help me: how can I display the output (image file name, mean color image, color histogarm) to see it, which I saved it in sruct of array in mat file
You can load mat files (MatLAB) formats in the free software GNU Octave.
Loading it would give you a new variable, let's say a
After you loaded it, you can display it according to the structure using octave commands.
GNU octave can be downloaded here: http://www.gnu.org/software/octave/download.html
Example hist(a)