Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB: Load files from folder by extension

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;
like image 803
sjas Avatar asked Apr 04 '13 12:04

sjas


People also ask

How do I get a list of files in a directory in MATLAB?

To search for multiple files, use wildcards in the file name. For example, dir *. txt lists all files with a txt extension in the current folder. To search through folders and subfolders on the path recursively, use wildcards in the path name.

What is Fullfile in MATLAB?

fullfile replaces all forward slashes ( / ) with backslashes ( \ ) on Windows. On UNIX® platforms, the backlash ( \ ) character is a valid character in file names and is not replaced. fullfile does not trim leading or trailing separators.

How do I copy a file in MATLAB?

copyfile(' source','destination',' f ') copies source to destination , regardless of the read-only attribute of destination . [status,message,messageid] = copyfile ('source','destination',' f ') copies source to destination , returning the status, a message, and the MATLAB error message ID (see error and lasterr ).


1 Answers

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".

like image 136
Eitan T Avatar answered Nov 07 '22 21:11

Eitan T