2

I'm trying to write a code in Matlab that will generate a plot into a figure and then save or export the figure into my directory. The code I used is as follow:

h = figure('name','HousingIndex');
plot(quarter,indexSample,quarter,indexSubsample);
legend('Index Sample','Index Repeat Subsample');
title('Housing Index');
xlabel('Quarter');
ylabel('Index');

Where "quarter" is a 1-by-75 vector of consecutive quarters and "indexSample" and "indexSubsample" are 1-by-75 vectors of indices values. However, when I try to export the figure using the hgexport function as such:

hgexport(h,'HousingIndex.jpg');

I received the following error message:

??? Error using ==> hgexport at 140
First argument must be a handle to a figure.

I also tried using the saveas function as such:

saveas(h,'HousingIndex.jpg')

and I received the following error message:

??? Error using ==> saveas at 59
Invalid handle.

Both errors indicate I have an invalid handle. I will greatly appreciate a descriptive answer of why I'm getting an invalid handle as well as a solution to this problem.

tshepang
  • 12,111
  • 21
  • 91
  • 136

1 Answers1

1

Experienced the same issue but found a way to do it:

figure
h = plot([1:5],[1:5])
print('testing', '-dpng')

The first one sets a new empty figure (maybe it can be done without this step, but it worked for me as is), and the last one creates a png file (hence -dpng) with the name 'testing' and the plot in h, and voila! It works :)

Anon
  • 619
  • 1
  • 9
  • 18