user2587726
user2587726

Reputation: 338

How to save a subplot in for loop?

Using this code to create and save a subplot automatically (in a for loop) is not working and throwing up an error I don't understand:

clear
clc
close all

%----------------------------
x1 = 1:0.01:3;
r = -1 + (1+1)*rand(1,201);
x1 = x1 + r;

y1 = 1:0.01:3;
r = -1 + (1+1)*rand(1,201);
y1 = y1 + r;

z1 = [1,2,3;4,5,6;7,8,9];

LC = 0

for nn = 1:10
    LC = LC+1
figure()
subplot(2,1,1)
scatter(x1,y1)
legend('Data')
subplot(2,1,2)
xvalues_HM = {'True label 1','True label 2','True label 3'};
yvalues_HM = {'Mdl label 3','Mdl label 2','Mdl label 1'};
h = heatmap(xvalues_HM,yvalues_HM,z1);

txtsave = [num2str(LC)];     
saveas(gcf,[ txtsave '.png']);
close all

end

I get this error message:

Error using alternatePrintPath
Dimensions of arrays being concatenated are not consistent.

Error in alternatePrintPath

Error in print (line 83)
pj = alternatePrintPath(pj);

Error in saveas (line 181)
        print( h, name, ['-d' dev{i}] )

Error in script (line 396)
        saveas(gcf,[ txtsave '.png']);

Which makes no sense - what array is it concatenating? This code works when I ask it to save a figure (i.e. not a subplot).

Issue seen using MATLAB R2020a.

Upvotes: 0

Views: 82

Answers (1)

user2587726
user2587726

Reputation: 338

I can produce this figRemoving the legend of the first figure now produces the desired subplot, albeit with unlabelled data.

As Hoki has linked to, this appears to be a bug with heatmaps around releases R2019b/R2020a.

Upvotes: 2

Related Questions