Create Matlab figures in LaTeX using matlabfrag or alternatives - matlab

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.

Related

How can I write with latex character in xlabel in matlab

I would write my xlabel with Latec character so I used this code
x = -10:0.1:10;
y = [sin(x); cos(x)];
plot(x,y)
xlabel('$\mathbb{x}$','Interpreter','latex')
but I have this warning message
Warning: Error updating Text.
String scalar or character vector must have valid interpreter syntax:
$\mathbb{x}$
and the xlabel appear like this
https://i.stack.imgur.com/NCI4n.png
please how I can fix this problem.
The problem with your example is the mathbb command, which is not in base Latex. To show this, replace the \mathbb with, e.g., \mathrm. This will work.
I've never seen an example of adding Latex packages into the Matlab environment. (Update below)
You can have a look at this question, which includes a very aggressive potential way to add the package you need. But it's not clear to me if the solution proposed is actually functional.
How do you use the LaTeX blackboard font in MATLAB?

How can I convert matlab code to image?

For exmaple,I have the following code.
% Generate random data from a uniform distribution
% and calculate the mean. Plot the data and the mean.
n = 50; % 50 data points
r = rand(n,1);
plot(r)
% Draw a line from (0,m) to (n,m)
m = mean(r);
hold on
plot([0,n],[m,m])
hold off
title('Mean of Random Uniform Data')
for v = 1.0:-0.2:0.0
disp(v)
end
I want to convert MATLAB code to an image.
For example, if you copy the MATLAB code into a software then it return the image like this:
How to do it?
If I use this code and publish it to PDF file,the code is not completely display.
sumLumi(x,y)=LLmap3(floor(x/4)+1,floor(y/4)+1)+LLmap3(floor(x/4)+2,floor(y/4)+1)+LLmap3(floor(x/4)+1,floor(y/4)+2)+LLmap3(floor(x/4)+2,floor(y/4)+2);
From the MATLAB editor you can Publish your document as a PDF (by changing the Output file format to pdf under publishing options). It will also evaluate the code unless you change the Publishing Options>Code Settings>Evaluate code to false.
The PDF can then can converted to an image (a quick google search gives an online PDF to JPG converter).
You can break a line and continue on the next with ..., for example
sumLumi(x,y)=LLmap3(floor(x/4)+1,floor(y/4)+1)+LLmap3(floor(x/4)+2,floor(y/4)+1)+LLmap3(floor(x/4)+1,floor(y/4)+2)+LLmap3(floor(x/4)+2,floor(y/4)+2);
can be written as
sumLumi(x,y) = LLmap3(floor(x/4)+1, floor(y/4)+1) ...
+ LLmap3(floor(x/4)+2, floor(y/4)+1) ...
+ LLmap3(floor(x/4)+1, floor(y/4)+2) ...
+ LLmap3(floor(x/4)+2, floor(y/4)+2);
If you want to use Matlab only you can use this workflow:
Make your code to be single .m file. Any text file will work.
Read this file in cell column vector Code;
Process the lines adding using TeX or LaTeX formatting commands;
Create white figure with text(x,y,Code);
Export the figure.
This might be good way to produce many figures with same style.

Save Figure generated from HeatMap() from Bioinformatics Library - Matlab

I would like to save the image I generate the HeatMap() function from the bioinformatics library.
I cannot figure out to have the image without manually exporting the data.
I'd prefer to use HeatMap over Imagesc because it automatically scales the data to the mean.
I do not have the Bioinformatics Library for matlab, However you should be able to get the current figure with the function gcf. It is not the most stable way, but in most cases this will work excellent. Then you can save the figure as a figure or image with saveas.
HeatMap(...);
hFig = gcf;
saveas(hFig,'myName','png'); % You can use other image types as well and also `'fig'`
There is a second way as well. The HeatMap class also contains a plot method. This method may return the figure handle to the HeatMap plot then save the image with saveas.:
hHM = HeatMap(...);
hFig = plot(hHM);
saveas(hFig,'myName','png');
I share a part of a Matlab code that I used when I analyzed some data from TCGA
#I was considering two gene expression level taken from cancer disead tissue and
# healthy tissues comparing them with this Heatmap
labela=Gene;
labelb=Gene2;
data1=[dataN(indg,:) dataC(indg,:); dataN(indg2,:) dataC(indg2,:);];
H=HeatMap(data1,'RowLabels',
{labela,labelb},'Standardize','row','Symmetric','true','DisplayRange',2);
addTitle(H,strcat('HeatMap',project));
addXLabel(H,'patients');
addYLabel(H,'geni');
#I have allocated the plot in a variable
fig=plot(H);
# Then I saved the plot
saveas(fig,strcat('D:\Bioinformatica\Tesina...
Prova2\Risultati_lihc\',dirname,'\HM.fig'));
But if you have to run one single object I advise against waisting your time in writing code (even if it is always a good thing to explore and strengthen your knowledge), I used because each time I was running a pipeline. Otherwise you can go on
1)File ----> Export Setup
2) Export
3)Save in the format you do want!

Simplest way to read space delimited text file matlab

Ok, so I'm struggling with the most mundane of things I have a space delimited text file with a header in the first row and a row per observation and I'd like to open that file in matlab. If I do this in R I have no problem at all, it'll create the most basic matrix and voila!
But MATLAB seems to be annoying with this...
Example of the text file:
"picFile" "subjCode" "gender"
"train_1" 504 "m"
etc.
Can I get something like a matrix at all? I would then like to have MATLAB pull out some data by doing data(1,2) for example.
What would be the simplest way to do this?
It seems like having to write a loop using f-type functions is just a waste of time...
If you have a sufficiently new version of Matlab (R2013b+, I believe), you can use readtable, which is very much like how R does it:
T = readtable('data.txt','Delimiter',' ')
There are many functions for manipulating tables and converting back and forth between them and other data types such as cell arrays.
There are some other options in the data import and export section of the Statistics toolbox that should work in older versions of Matlab:
tblread: output in terms of separate variables for strings and numbers
caseread: output in terms of a char array
tdfread: output in terms of a struct
Alternatively, textscan should be able to accomplish what you need and probably will be the fastest:
fid = fopen('data.txt');
header = textscan(fid,'%s',3); % Optionally save header names
C = textscan(fid,'%s%d%s','HeaderLines',1); % Read data skipping header
fclose(fid); % Don't forget to close file
C{:}
Found a way to solve my problem.
Because I don't have the latest version of MATLAB and cannot use readable which would be the preferred option I ended up doing using textread and specifying the format of each column.
Tedious but maybe the "simplest" way I could find:
[picFile subCode gender]=textread('data.txt', '%s %f %s', 'headerlines',1);
T=[picFile(:) subCode(:) gender(:)]
The textscan solution by #horchler seems pretty similar. Thanks!

matlab printing splitted plot to file

I'm creating a code to do data analysis that will run on a server. The code is supposed to spit a pdf file with 3 plots on it.
I have created a code that generates the plot
fig = figure;
for i = 1:3
%do some calculation to find, X, Y and fit
subplot(3,1,i)
scatter(X,Y)
hold on
plot(X,fit)
end
print (fig, '-dpdf','fig.pdf')
X, Y, and fit are calculated/imported parameters. The output of this code is a pdf document with only the last plot on it (missing the first two).
How can I print all three of them to file?
I tried your code on my CPU (X,Y and fit were generated randomly) and it works fine, so the bug may come from the interaction of this snip of code with you "%do some calculations block"
I would suggest to add a "hold off" command before the end of the for loop ...
gus