MATLAB Answers


Read certain files from a directory in matlab?

Asked by Jay
on 25 Jan 2013


I have over 100 .mat files in a directory and I am wondering how can I read and plot some of them. For example the file names are like such:

XX11YZ08 , XX12YZ07, XX13YZ08, XX14YZ06, XX15YZ08, and so on...

I would like to read and plot the data from all the files whose name end with '08'.

Thanks a lot in advance



No products are associated with this question.

2 Answers

Answer by Daniele
on 25 Jan 2013
Edited by Daniele
on 25 Jan 2013
 Accepted answer

Hi you can begin your m-file with dir() like


then create a cicle (for,while..)

in this cicle use string functions for comparing only last 2 character of the filename (before ".extension" obviously) with the string "08" and save the filenames that match with this condition in an array

after that use load()

mydata=load('myxxxyxylile08.mat'); and so plot data.

good luck


on 25 Jan 2013

Thanks Daniele. I got it to read the specific files like such:

files = dir(fullfile('D:\MyFolder\', '*08.mat'))

L = length(files);

for i=1:L


filepath = fullfile( 'D:\MyFolder\', file )


How do I now create an iterative loop which loads the data from each file and plots it on a single axes as overlaying plots?

Shashank Prasanna
on 25 Jan 2013

start loop load, plot, hold on maybe clear variable or overwrite if you are running our of memory end loop

Answer by Nike
on 25 Jan 2013
Edited by Nike
on 25 Jan 2013

Load the file within the 'for' loop and use the plot command followed by 'hold on' (use the hold on and plot within the loop)

if you want each to be in a different color, then you may have to create a string array with the colour codes and use them in the plot command with the (i),,,

Hope this helps


  1 Comment

on 27 Jan 2013

Thanks Nike.

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi test

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!