MATLAB: How to save the plots with file names from a string in the loop

loopplotsaveassavefigstring

filedata = dir('myfolder'); %Create information on files in folder
count = length(filedata); %Determines the number of files in the folder
filenames = {filedata.name}';%Creates a column vector with the names of files
fileloc ='myfileloc'; %Creates file trajectory for easy reference in loop
for i = 4:count matrix{i-3} = dlmread(fullfile(fileloc,filenames{i}),'',38,0);%Creates a matrix for each file in filnames, excluding first 3 files end
z = length(matrix);
for k = 1:z a = matrix{1,k};
hold on
h = figure(k)
plot(a(:,1),a(:,2))
title(filenames{k+3})
xlabel('Period (sec)')
ylabel('Acceleration (cm/s^2)')
saveas(h,filenames{k+3},'fig')
hold off
end
Returns the following error:
Error using saveas (line 166) Unsupported format or extension: tra
Error in processingfile (line 25) saveas(h,filenames{k+3},'fig')
I want to name my plots the same as the file names in the filenames vector.. How do I do this?

Best Answer

Add '.fig' to each filename
saveas(h, [filenames{k+3} '.fig'], 'fig')
Also try to reconsider your approach when you add 3 to k and subtract 3 from i in the loops, as this will most likely cause a lot of confusion in the future ...