trying to store figures in an array, in a loop, instead of printing each figure

4 views (last 30 days)
alex moore
alex moore on 28 Nov 2021
Commented: alex moore on 29 Nov 2021
Hi, I'm doing facial recognition using PCA. I am using the imagesc and colormap functions to generate an image based on the number of PCA's used however, i am incrementing the number of PCA's used each iteration, for 5 different pictures so MATLAB is plotting 50 different figures each time I run the program. Is there a way to use those functions to simply store the figure, each iteration through the loop, in an array where I can access them separately instead of 50 images popping up each time I run the program?
my code shown below (note: faceR is a table of data, faces is a column vector with the face numbers, eigenfaces is an array of 99 eigenfaces, mean_face is an array of the mean faces)
fig = 1;
for i = 1:5
j = 1;
c = 1;
row = find(faceR.VarName1==faces(i));
while j<100
v = rows2vars(PCA_faceR(row,1:j));
k = eigenfaces(:,1:j)*v.Var1+mean_face';
imagesc(reshape(k,128,128)');
figure(fig);
colormap(gray(256));
j = j+10;
c = c+1;
fig = fig+1;
end
end

Answers (1)

DGM
DGM on 28 Nov 2021
Since you're just using the gray colormap, there really isn't much that needs to be done. You can use mat2gray() to normalize the image to its extrema. This replicates the behavior of how imagesc() handles the colormap scaling. After that, there's no use for the figure() and colormap() calls. The output can be dumped into a cell array or into a multidimensional numeric array. For the sake of this example, I used a cell array.
allimg = cell(50,1);
aidx = 1;
for i = 1:5
j = 1;
c = 1;
row = find(faceR.VarName1==faces(i));
while j<100
v = rows2vars(PCA_faceR(row,1:j));
k = eigenfaces(:,1:j)*v.Var1+mean_face';
allimg{aidx} = mat2gray(reshape(k,128,128)');
aidx = aidx+1;
j = j+10;
c = c+1;
end
end

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!