MATLAB Answers

Create a figure -exactly- a certain size

78 views (last 30 days)
Theo on 27 Jul 2012
Consider the following code:
N = 2000;
[X,Y] = meshgrid(linspace(0,2*pi,N),linspace(0,2*pi,N));
Z = sin(X+Y);
p = pcolor(X,Y,Z)
Effectively, this colors each of the NxN elements of the matrix Z a given color. If you're running this, change N to something smaller.
I want to generate a .png figure that is exactly N x N pixels, each pixel representing one of the elements of Z.
How would I do that?
Additional notes:
This almost does it.
set(p, 'EdgeColor', 'none');
set(gca, 'Visible', 'off')
set(gcf, 'Units', 'pixels', [100 100 N+200 N+200]);
set(gca, 'Units', 'pixels', [50 50 N N]);
export_fig 'test' -png
This uses the export_fig package to create a tightly cropped figure.
There are two problems with this code:
  1. If N is large, then the figure is the incorrect dimension. For example, if N = 2000, then it seems that the figure gets expanded only until the height of your screen is reached. I need to be able to create arbitrarily sized images. The screen display is not important.
  2. The resultant figures are N+2 times N+2 pixels. I think that it's the 'removed' axes borders. How do I make it exactly N x N pixels (without cropping or re-sizing with an image editor)?


Ryan on 27 Jul 2012
What are you using the images for that you can't afford to have the 2 extra pixel rows in each dimension?
Does this help with the N=2000 issue?
set(FigureHandleName,'Position',[1 1 2000 2000])
Theo on 27 Jul 2012
I'd like to output the .png in order to use it as a texture for 3d models. No, it's not a huge deal, but I figured that it's a fairly simply issue which must have a simple solution. For a surface with many points, it will not be a big deal. But if the surface only consists of say, 10x10 points, then your pixel coloring will be off by 1.
Unfortunately, your suggestion does not work. If you try that, you'll see that the outputted image is rectangular. Using 2200 by 2200 for the figure window and 2000 by 2000 for the axis, it gives me a 1914 by 517 picture.

Sign in to comment.

Accepted Answer

Oliver Woodford
Oliver Woodford on 8 Aug 2012
export_fig (or rather, print) appears to only export that part of the figure which is on screen. Make the figure small and use the -mX option. E.g. make the axes half the size and use -m2. The output then still won't be exactly right, but a simple solution is to crop the image programmatically.


Sign in to comment.

More Answers (0)

Sign in to answer this question.