Save images in for loop without overwrite
9 次查看(过去 30 天)
显示 更早的评论
Hi All,
I'm currently running a loop through wav files, running spectrograms and wanting to save the spectrogram figure as a png file. I am wanting to save the images in a specific file but cant seem to work that out. I want the png file name to match the 'fname' also but cant work that out. The code I'm using does save the figure into the 'current folder' window of MATLAB, but as soon as the loop runs through again that file is replaced by the consecutive figure. Any help would be great. Please said my code below.
for i = 1: length(d); % loop over wav files
[pathstr,fname,ext] = fileparts(d(i).name);%fname is file name
[wf, fs] = audioread([WavDir, d(i).name]); % read 1 wav file at a time: waveform and fs
p = wf(:,ch2use); clear wf; % if multiple channels, pressure p is now just one channel
callin = 10.^(abs(cal)/20); p2 = p * callin; clear p; % p2 is now calibrated pressure
NFFT = fs; % window length = 1 s if NFFT = fs
[S,F,T,P] = spectrogram(p2,NFFT,NFFT/2,NFFT,fs,'yaxis');
% spectrogram(X,WINDOW,NOVERLAP,NFFT,Fs)
PSD = 10*log10(P); % dB
figure(1); clf; h = pcolor(T, F, PSD); set(h,'EdgeColor','none');
shading interp; set(gcf,'Renderer','zbuffer'); set(gca, 'YScale', 'log');
caxis([40 120]); colormap(jet); set(gca,'ylim',[10 fs/2]);
set(gca,'tickdir','out');
xlabel('Time [s]'); ylabel('Frequency [Hz]'); title(fname);
h1 = colorbar('peer',gca); set(get(h1,'ylabel'),'String','PSD [dB re 1 \muPa^2/Hz]');
save([ResDir,fname,'.mat'],'PSD', 'F', 'T', 'fs')
fname % write to screen to monitor which file is being processed
saveas(figure(1),'fname.png')
clf(figure(1))
end % loop over wav files
Also other code I've attempted:
%worked but doesnt save different file only overwrites the same file and puts it
%in the data part to the left
saveas(figure(1),'fname.fig')
%below also worked but still overwriting files
savefig(figure(1),sprintf('figure%d.fig'))
%below didnt work I believe because i havent created a funtion of what
%figure%d is, like how said what psd, f,t,fs is above
savefig([ResDir,fname,'.png'], 'figure%d')
%below also didnt work
q=figure(1)
savefig([ResDir,fname,'.png'], 'q')
%below didnt work, said unrecognised function or variable for fighandles
i = 1 : length(fighandles)
filepath = fullfile(source,sprintf('specs.png',figname{i,1}))
saveas(fighandles(i), filepath)
0 个评论
回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Time-Frequency Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!