This article is mostly sourced from the internet, and has been refined through the author’s own use, combined with personal experience and thoughts, to make using Matlab more convenient. Recording this serves two purposes: to help myself and to assist fellow netizens. Feel free to leave comments for discussion.
Table of Contents
1. Set the default text interpreter for the figure window to latex
2. Maximize the figure window
3. Dual axes
4. Timing
5. Local zoom on subplots
6. Scale font in figures
7. Legend marker and line property manipulation (multiple legends, reducing marker count)
8. EPS images not fully displayed in LaTeX
9. Axes obscured and disappearing after saving
10. Use all or specific files in a directory
11. [Original] Annotating EPS images using implicit information
12. Generate high-quality transparent vector graphics
13. Handling NaN in imagesc
14. Saving true vector EPS images with large datasets
15. Maximizing axes in figures
16. Embedding fonts in EPS images
17. Clever methods for using a single color in surfaces
1. Set the default text interpreter for the current figure window to latex:
set(gcf,'DefaultTextInterpreter','latex')
This can also be generalized:
set(0,'DefaultTextInterpreter','latex')
However, it seems that the legend’s interpreter is not affected by this setting? (You can set it using ‘Interpreter’,’latex’, but it still feels unsatisfactory.)
2. Maximize the figure window:
set(gcf,'outerposition',get(0,'screensize'))
3. Dual axes
[hax,hl1,hl2]=plotyy([x1,y1,x2,y2],[x3,y3]);
This will plot two curves (x1,y1) and (x2,y2) on the left axis, and one curve (x3,y3) on the right axis.
Some settings for the axes can be manipulated through the return values.
set(gcf,'CurrentAxes',hax(1)) // Set the current axes to the left axis
set(gca,'Ylabel','xxxx') // Now you can operate on this axis normally, and use hold on to add curves
4. Timing
t0 = cputime; % program; time=cputime-t0;
tic; % program; toc;
t0 = clock; % program; time = etime(clock, t0);
5. Local zoom on subplots
There is an extension called mmzoom that allows you to zoom in on a selected area with the mouse, which works well but is not conducive to precise control.
In fact, creating your own subplot is not difficult:
myzoom([0.18,0.18,0.4,0.3],[x0,x1,y0,y1])
This is achieved using a simple function written by the author:
function myzoom(position,axiscale)
ha=get(gcf,'CurrentAxes');
ha1=copyobj(gca,gcf);
set(ha1,'position',position)
set(gcf,'CurrentAxes',ha1)
axis(axiscale)
xlabel('')
ylabel('')
set(gcf,'CurrentAxes',ha)
Here, position is the relative position and size of the subplot in the current figure, and [x0,x1,y0,y1] are the coordinate limits you want to zoom in on.
6. Figure font scaling issue
Make the font size change according to the scaling factor you set:
hf=figure;
fp=get(hf,'position');
times=2.0; % Custom scaling factor,
set(hf,'position',[0 0 times*fp(3:4)]) % Scale the figure
set(gca,'FontSize',times*get(gca,'FontSize')) % Scale font size on gca
xlabel('X') % Label should be set after adjusting gca font size, no need to set it separately
ylabel('Y')
hc=colorbar;
set(hc,'FontSize',times*get(hc,'FontSize')) % Assuming there is a colorbar, which is actually another axes, set its font size the same way
Reference: http://blog.csdn.net/benjmzhu/article/details/7246870
Only after looking at this did I realize that the output format can also be set in Export Setup, and that
set(findall(gcf,'-property','FontSize'),'FontSize',12)
can change the font size of all objects to 12!
7. Legend marker and line operations
In cases where there are too many curves, using line styles alone is not sufficient; you can only use a combination of markers, colors, and line styles. Generally, journals require that each curve’s significance can be understood without color, so you can only use a combination of markers and line styles. However, if your data points are too numerous, resulting in too many markers, it becomes impossible to see clearly.
The simplest solution to this problem is: … haha, directly call an existing function (the author has made some revisions to the original to ensure it works even when the horizontal and vertical axis ranges differ greatly; you might also want to consider log scales), and when using legend afterwards, this function will not affect the legend:
“nummarkers.m” http://pan.baidu.com/share/link?shareid=1072992811&uk=151290240
The method I used previously is actually based on the same principle; I also plotted the different colored curves with lines, and then redrew each curve with fewer markers. This way, the legend display needs to be customized for the line styles and colors.
x=0:0.0001:2*pi;
y1=sin(x);y2=cos(x);
figure
hold on
box on
n=1000;
hl(1)=plot(x(1:n:end),y1(1:n:end),'rd');
hl(2)=plot(x(1:n:end),y2(1:n:end),'go');
lstr={'sin(x)','cos(x)'};
plot(x,y1,'r')
plot(x,y2,'g')
[hleg chleg hplot hlabel]=legend(hl,lstr,'location','southwest'); % hplot, hlabel can be replaced with ~ in R2013a
set(chleg,'linestyle','-')
What is puzzling is when operating on the objects contained in chleg separately; for example,
set(chleg(1),'linestyle','.-')
seems to work fine when viewed with
get(chleg(1))
, but there is no effect on the plot!!!
Reference:
http://www.mathworks.com/matlabcentral/newsreader/view_thread/96754
http://www.mathworks.com/matlabcentral/answers/49027
There is also a clever method:
http://blog.sciencenet.cn/blog-43412-45936.html
8. The issue of EPS images not being fully displayed in LaTeX.
This manifests as EPS images inserted into LaTeX being partially cut off in the PDF. The reason is that the papersize setting of the EPS image is too small, causing the image to exceed the paper’s range. (I also don’t quite understand what bounding box and papersize are; in MATLAB, there is also a paperposition setting, which corresponds to the bounding box, right? Setting papersize to A0, but the printed image is compact, and the size is not this papersize!) Here is the command solution I used:
set(gcf,'PaperType','A0')
set(gcf,'PaperPositionMode','auto')
print('filename','-depsc');
According to MATLAB’s help file, it is best to set PaperType after setting PaperUnits. Of course, PaperSize can be set by yourself (PaperType only provides a few defaults: http://en.wikipedia.org/wiki/Paper_size#C_series).
set(gcf, 'PaperUnits', 'inches');
set(gcf, 'PaperSize', [5 7]);
Reference: http://blog.sciencenet.cn/blog-533656-428329.html http://blog.renren.com/share/236157660/13151799720 http://nibot-lab./73290.html
http://blog.sciencenet.cn/blog-471076-381288.html http://blog.sina.com.cn/s/blog_618af1950100jipf.html
9. Axes obscured and disappearing after saving
set(gca,'Layer','top') % Axes obscured
set(gca,'LineWidth',2) % Axes may disappear after saving as a PNG due to being too thin (this has troubled me for a long time; for example, using patch to set transparency or using pcolor may cause axes to disappear)
10. Use all or specific files in a directory
files=dir('*.txt');
for i=1:length(files)
a=load(files(i).name);
end
Note that using the dir command directly in Linux will yield all files and directories (files.isdir=1), and the current directory “.” and the parent directory “..” will also be included.
If you write your own, you might consider using the system command combined with regexp(str,’\t+\s+’,’split’) in Linux, but it’s quite cumbersome compared to using dir directly.
11. Annotating EPS images using implicit information
Since EPS images contain some header information describing the filename, title, creator, etc., we can place some information that does not need to be displayed in the figure but is still necessary into the implicit comment information of the EPS file. (This way, the information will not easily change with the filename. Does this remind you of exons and introns in gene sequences? Perhaps the introns in human genes are annotations or backdoors implanted by the creator, haha…)
So how do we put it in? Actually, EPS is text-based, so you can open it as a text document for editing! So in MATLAB, how do you do it? Place the information you want to write into a string, and then replace or add some comment information in the EPS file!
Currently, I’m not very familiar with string replacement operations in MATLAB, so I’ll just provide an example using the sed command in a Linux system to add information:
info='Hello, World!';
eval_r(['!sed -i ''s/\(\%\%Title.*\)/\%\%',info,'/g'' test.eps'])
Thus, after opening it with an image viewer and checking the document’s “properties”, you can see that the title has changed to “Hello, World!”.
12. Generating high-quality transparent vector graphics (not fully tested)
12.1 How to set NaN data in color maps to white while ensuring the output quality.
http://www.mathworks.com/matlabcentral/newsreader/view_thread/140607
The third method here is the best, although a bit complex, it ensures that data is displayed correctly while producing small, high-quality output images.
Methods like pcolor or
set(h,'alphadata',~isnan(C))
will produce large, low-quality EPS images due to transparency settings: axes disappearing, text being jagged.
12.2 3D plots
http://www.mathworks.com/matlabcentral/newsreader/view_thread/158841
print -depsc2 -painters test3.eps
can solve some issues with low-quality output for 3D plots, but there may be problems when outputting images with transparent data?
12.3 Transparent images
http://www.myoutsourcedbrain.com/2009/07/produce-print-quality-figures-from.html
13 Handling NaN in imagesc (to be considered for a perfect solution later)
Why doesn’t MATLAB set the default color for NaN in imagesc to white?
pcolor does this, but imagesc does not, how is it considered? I can’t understand!
13.1 Ready-to-use m-file, set to any color:
https://gist.github.com/zertrin/5553630
13.2 The simplest line (if you save it as an EPS image, you may find this a tragedy):
h=imagesc(C)
set(h,'alphadata',~isnan(C))
13.3 Create your own color map, converting NaN:
http://www.mathworks.com/matlabcentral/newsreader/view_thread/33744
14 Saving true vector EPS images with large datasets
When MATLAB encounters large datasets, even if you want to save as EPS vector graphics, it actually outputs a rasterized version first and then converts it to EPS. Thus, the saved EPS images are of poor quality, and the text cannot be edited when inserted into LaTeX.
The following method will not have issues:
print(gca,'-depsc2','painters',filename)
Reference: http://stackoverflow.com/questions/8280971/matlab-and-high-quality-eps-figures
(There is also an export_fig file and savesvg file extension that seems very powerful, but I haven’t tried them.)
15 Maximizing axes in figures
tightInset = get(gca, 'TightInset');
position(1) = tightInset(1);
position(2) = tightInset(2);
position(3) = 1 - tightInset(1) - tightInset(3);
position(4) = 1 - tightInset(2) - tightInset(4);
set(gca, 'Position', position);
saveas(h, 'WithoutMargins.pdf');
Source address: http://stackoverflow.com/questions/5150802/how-to-save-a-plot-into-a-pdf-file-without-a-large-margin-around
16 Embedding fonts in EPS images
The export_fig file is very useful and can solve the EPS font embedding issue:
http://btstream.is-programmer.com/posts/24988.html
Other solutions:
http://blog.sina.com.cn/s/blog_a3b1929c0100zh5b.html
17 Clever methods for using a single color in surfaces
[x,y]=meshgrid(-8:0.1:8);
z=x.^2+y.^2;
k=ones(size(z));
hsf=surf(x,y,z,k);
alpha(hsf,0.5)
colormap([0 0 1])
shading flat
Source: http://www.ilovematlab.cn/thread-54614-1-1.html
This article is reprinted from felonwan’s Sina blog
Original link: http://blog.sina.com.cn/s/blog_59cf672601015qmm.html
