HW#3 - I could not get a script to open multiple files in one script. If possible, would you be able to go over this in class as it would benefit all the students in the class to ensure they have this concept down; it would be much appreciated.

JFF Answer:

Generally speaking you should NOT open multiple files at one time because it takes more memory to keep multiple files open at one time. A better approach would be to open ONE file at a time, read in the data, process data/ save results in variable in matlab, and then CLOSE the file before opening a second file.

Sometimes this is best accomplished using a FOR loop. See sample code below. To open MULTIPLE FILES at same time, just use MULTIPLE fopen commands as in

fileIDa = fopen('myfileA.txt','r');

fileIDb = fopen('myfileB.txt','r');

fileIDc = fopen('myfileC.txt','r');

of course, now when you read in the data, with the textscan command, you must specify the correct fileID to read in the data form the different files.




% define a string array of the base file names. This works well if there

% are only a few number of names.

%% Initialize variables.

delimiter = '\t';

startRow = 3; 

%% Format for each line of text:

%   column1: double (%f)

%   column2: double (%f)

% For more information, see the TEXTSCAN documentation.

formatSpec = '%f%f%*s%*s%*s%*s%*s%*s%*s%[^\n\r]';

for i=[1:Nfiles];


%% Open the text file.

fileID = fopen(myFileName,'r');


%% Read columns of data according to the format.

dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'TextType', 'string', 'HeaderLines' ,startRow-1, 'ReturnOnError', false, 'EndOfLine', '\r\n');


%% Close the text file.



%% Allocate imported array to column variable names

time = dataArray{:, 1};

voltage = dataArray{:, 2};


% now put in code to process time and voltage as needed....



%% Clear temporary variables

clearvars delimiter startRow formatSpec fileID dataArray;