Reputation: 19677
What is the easiest way to load all files from a folder with the same extension into MATLAB?
Previous solutions by me:
%%% Will load a file if its filename is provided
%%% USAGE: (Best save data to a variable to work with it.)
%%% >> x = loadwrapper('<file_name>')
%%% ... and then use 'x' all the way you want.
%%% <file_name> works with absolute and relative paths, too.
function [ loaded_data ] = loadwrapper( file_name )
files = dir(file_name);
loaded_data = load(files.name);
end
and
%%% put this in a new script, in a function it WILL NOT WORK!
%%% and fix your paths, ofc. i left mine in here on purpose.
%%% SETTINGS
folderName='/home/user/folder/';
extension='*.dat';
%%% CODE
concattedString=strcat(folderName, extension);
fileSet=dir(concattedString);
% loop from 1 through to the amount of rows
for i = 1:length(fileSet)
% load file with absolute path,
% the fileSet provides just the single filename
load (strcat(folderName, fileSet(i).name));
end
%%% TIDY UP
%%% only imported files shall stay in workspace area
clear folderName;
clear extension;
clear concattedString;
clear fileSet;
clear i;
Upvotes: 5
Views: 19718
Reputation: 431
If you want to import all the functions from a directory, you can use addpath :
In matlab you are in the c:\matlab\work directory and you tap :
addpath directory_where_all_my_functions_are
to import all the function of the c:\matlab\work\directory_where_all_my_function_are
help addpath
in matlab for more information
Upvotes: 1
Reputation: 32930
You can use dir
to get all desired files. Then you can iterate over them with a for loop and call load
for each. For example, the following:
files = dir('C:\myfolder\*.txt');
for k = 1:length(files)
load(files(k).name, '-ascii')
end
loads all files in "C:\myfolder" with the extension "txt".
Upvotes: 7