Ali
Ali

Reputation: 33

Saving multi-files which is imported using importdata

I am using below code to read multi-files using importdataand forcommands. The problem that I have is only the last file is saved . I got from importdataone matrix but it should be 6 matrices

How I can save all matrices that I imported?

myFolder = 'M:\Matlab\Experiment-Result\read all';
filePattern = fullfile(myFolder, '*.dat')
theFiles = dir(filePattern);
for k = 1 : length(theFiles)
    baseFileName = theFiles(k).name;
    fullFileName = fullfile(myFolder, baseFileName);
    fprintf(1, 'Now reading %s\n', fullFileName);
    Data = importdata(fullFileName);
end

Upvotes: 2

Views: 37

Answers (1)

rayryeng
rayryeng

Reputation: 104555

Very simple reason. Data keeps getting overwritten at each iteration of the loop and so once the for loop stops, only the data read in from the last iteration gets saved. If you want to save the data per iteration, I don't know how your data is structured, but to make it the most adaptable, make Data a cell array:

myFolder = 'M:\Matlab\Experiment-Result\read all';
filePattern = fullfile(myFolder, '*.dat')
theFiles = dir(filePattern);
Data = cell(1,numel(theFiles)); %// Change
for k = 1 : length(theFiles)
    baseFileName = theFiles(k).name;
    fullFileName = fullfile(myFolder, baseFileName);
    fprintf(1, 'Now reading %s\n', fullFileName);
    Data{k} = importdata(fullFileName); %// Change
end 

To access the kth data file, simply do:

out = Data{k};

You can then use out as if it were a matrix and index / slice into it in however manner you see fit.

Upvotes: 1

Related Questions