user1554925
user1554925

Reputation: 55

cd error - file path not character vector Matlab

This is probably and easy matlab question but I am really struggling with this one:

I am building a for loop to go through a directory of folders and open a file (filename.csv) within each uniquely named folder. Thus, I have defined my filepath within my loop so that it opens each correct folder and then the correct file within. I am getting hung up, however, on simply concatenating my filepath within the loop, changing the directory to the appropriate folder and then opening the file. Here is the code (outside the for loop with just i=1, for simplicity sake):

drive = dir()
namelist = dir(drive)
filepath = strcat(drive, namelist[1])
cd(filepath)
x = xlsread('filename.csv')

I have also tried defining the filepath as the path of the file itself:

filepath = strcat(drive, namelist[1], '\filename.csv')
x = xlsread(filepath)

Both methods produce an error message when using cd or when using xlsread that 'arguments must contain a character vector'.

I have also tried using fullfile instead of strcat, to no avail.

Upvotes: 1

Views: 428

Answers (1)

Banghua Zhao
Banghua Zhao

Reputation: 1556

dir() return a struct array in your current directory. So drive = dir() will give you a struct array drive. For example:

drive = 
  81×1 struct array with fields:
    name
    folder
    date
    bytes
    isdir
    datenum

According to your problem, first, to get a list of directory names, you can do this:

drive = dir()
namelist = {drive([drive(:).isdir]).name}

This will give you a cell array of directory names.

Since . and .. are the current directory and parent directory. You might want to delete these two (Usually, they are the first and second element):

namelist(1) = []
namelist(1) = []

Then, to get to the path of those directories, you can do this:

for i =1:length(namelist)
    filepath = strcat(pwd, '\', namelist{i},'\filename.csv')
    x = csvread(filepath)
end

Upvotes: 1

Related Questions