change figure size, but keep the position in center in matlab

You can change the figure size and keep the position centered using the following code:

main.m
% create a plot
x = 1:10;
y = sin(x);
plot(x,y)

% get the current figure position and size
fig = gcf;
fig_pos = fig.Position;
fig_width = fig_pos(3);
fig_height = fig_pos(4);

% set the new figure size (50% larger)
fig_width_new = fig_width * 1.5;
fig_height_new = fig_height * 1.5;
fig_pos_new = [fig_pos(1)-(fig_width_new-fig_width)/2, fig_pos(2)-(fig_height_new-fig_height)/2, fig_width_new, fig_height_new];

% set the new figure position and size
fig.Position = fig_pos_new;
481 chars
19 lines

This code creates a plot and then gets the current figure position and size using gcf (get current figure), which returns a handle to the current figure. It then calculates the new figure width and height (here, 50% larger) and the new figure position based on the current position, and sets these using the Position property of the figure handle.

Note that this code assumes that the current figure is in the center of the screen. If the figure is not centered, you may need to adjust the calculation of the new position accordingly.

related categories

gistlibby LogSnag