MATLAB: Run script for multiple files with similar names and save outputs

dynamically named variablesevalfunctionloopplottingtextscan

I have a script that I am using to extract data from a .dat file and plot column one against column 3 + column 5. The file numbers I am using range from 050 to 200 in increments of 10. By calling the function with the filenumber the scripts runs and save the plot to both .fig and .jpeg formats.
I would like to make this script run automatically for all 16 .dat files. I am also trying to rename the variable max_f to maxf_re**0, then save the maxf_re**0 into a table and plot it against the filenumber.
Below is the function I currently have
function [] = import_data(filenumber)
%filename = 'C:\.....\MATLAB\forces_re**0.dat';
pre = 'C:\......\MATLAB\forces_re';
post = '.dat';
filename = strcat(pre,filenumber,post);
startRow = 3;
formatSpec = '%16f%16f%16f%16f%16f%16f%16f%16f%16f%f%[^\n\r]';
fileID = fopen(filename,'r');
dataArray = textscan(fileID, formatSpec, 'Delimiter', '', 'WhiteSpace', '', 'EmptyValue' ,NaN,'HeaderLines' ,startRow-1, 'ReturnOnError', false);
fclose(fileID);
% Allocate imported array to column variable names
t = dataArray{:, 1};
l = dataArray{:, 3} + dataArray{:, 5};
% Plot both figures into seperate windows:
h = figure;
subplot(1,2,1)
plot(t,l)
[p,f,max_f] = myspectrum (t,l,1);
subplot(1,2,2)
plot(f,p),axis([0 1 0 0.01])
% Save plot to .jpeg and .fig formats:
hgexport(gcf, strcat('forces_re',filenumber,'.jpg'), hgexport('factorystyle'), 'Format', 'jpeg');
savefig(h,strcat('forces_re',filenumber,'.fig'))
end

Best Answer

"I would like to make this script run automatically for all 16 .dat files"
This is easy. Here are three easy ways to generate the filenames:
  • Use dir to get a list of files in a directory.
  • Create the filenames in a loop using sprintf, int2str, if the files are numbered sequentially.
  • Keep the list of filenames in a cell array.
This link explains how to do this in more detail. Please read both examples carefully:
You might also like to consider putting the file-processing code in a function, which could then be called in a loop from another function. Abstraction like this can make code more robust and encourages code re-use and planning.
"I am also trying to rename the variable max_f to maxf_re**0"
This is a bad idea.
You should avoid dynamically naming variables like this. Instead you should simply store the matrices in a cell array, a structure or perhaps a simple numeric array with the correct array preallocation. To know why it is a bad idea to create dynamically named variables, read this link carefully: