How to access folders within a loop

2 views (last 30 days)
Daphne PARLIARI on 11 Jan 2020
Commented: Stephen23 on 12 Jan 2020
Hello guys!
I am struggling to do something that I don't know if it's possible but let's give it a try.
I have a set of data I want to access and since they are quite a few, I want to do it within a loop. To do so, I created a .txt (see attached) and based on its columns (Station and Network), I want to navigate through the respective directories.
To give an example, if the station is Airport and the network is EMY (as appeared in the .txt), I want the code to be able to find and read the file C:\PhD\Projects\LIFE ASTI\C.3\Weather station data\from desktop\Obs. data 4 Keppas\EMY\2015\Airport.xlsx
obsdir='C:\PhD\Projects\LIFE ASTI\C.3\Weather station data\from desktop\Obs. data 4 Keppas'
stations = readtable('C:\PhD\Projects\LIFE ASTI\C.3\Weather station data\from desktop\Stations coordinates3.txt');
for i=1:size(stations,1)
name = stations( i, 1 );
network = stations (i, 'Network');
lat = stations(i, 'Lat' );
lon = stations(i, 'Lon' );
networkstr = char(network.(1));
namestr = char(name.(1));
[obsdata,txt,raw] = xlsread([obsdir,'\',networkstr,'\', '2015','\','Airport.xlsx']);
Of course I am getting two errors!
Error using xlsread (line 132)
XLSREAD unable to open file 'C:\PhD\Projects\LIFE ASTI\C.3\Weather station data\from desktop\Obs. data
4 Keppas\MoT\2015\Airport.xlsx'.
File 'C:\PhD\Projects\LIFE ASTI\C.3\Weather station data\from desktop\Obs. data 4
Keppas\MoT\2015\Airport.xlsx' not found.
Error in Untitled3 (line 23)
[obsdata,txt,raw] = xlsread([obsdir,'\',networkstr,'\', '2015','\','Airport.xlsx']);
Is there any idea please??

Answers (1)

Meg Noah
Meg Noah on 12 Jan 2020
Edited: Meg Noah on 12 Jan 2020
Try this (in absence of the Airport.xlsx files I can't completely test it here) - edit the obsdir back to your folder name where the files are:
stations = readtable(fullfile(obsdir,'Stations coordinates3.txt'));
for istation=1:size(stations,1)
name = stations.Station{istation};
network = stations.Network{istation};
lat = stations.Lat(istation);
lon = stations.Lon(istation);
[obsdata,txt,raw] = xlsread([obsdir,'\',network,'\', '2015','\','Airport.xlsx']);
  1 Comment
Stephen23 on 12 Jan 2020
It is recommended to use fullfile rather than concatenating strings together. Instead of
[obsdir,'\',network,'\', '2015','\','Airport.xlsx']
just use fullfile like this (it automatically handles the file separator character):

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!