1
votes

I have a list of names in a text file, and I want to read each name and then check if a directory exists with that name. However, I am having a little trouble understanding cell arrays, and my current implementation is not running as expected.

Below is my code:

% Read in the directory names from the text file
file_id = fopen('myfile.txt');
line = fgetl(file_id);
lines = [];
while ischar(line)
    lines = [lines; line];
    line = fgetl(file_id);
end

% Create a cell array from the character array
lines = cellstr(lines);
num_dirs = size(lines, 1);

% Loop through all directory names
for i=1:num_dirs
    % Check if the directory exists
    dir_name = lines(i, 1);
    if exist(my_dir, 'dir')
        % Do something
    end
end

This crashes at the line if exist(my_dir, 'dir'). It appears that dir_name is a 1x1 cell, rather than a string as I would like, which I think may be causing this.

So how can I read in these names from the text file, and then load each name, such that I load a string, rather than a cell? I find cells very confusing!

1

1 Answers

1
votes

You can access the content of a cell in a cell array by indexing with curly braces. I have created a myfile.txt containing the lines

file1
file2
file3

in order to test your code.

...
>> lines = cellstr(lines);
>> lines{1}    
ans =
    file1
>> whos ans
  Name      Size            Bytes  Class    Attributes

  ans       1x5                10  char 

Notice the difference when indexing with parenthesis:

>> lines(1)
ans = 
    'file1'
>> whos ans
  Name      Size            Bytes  Class    Attributes

  ans       1x1               122  cell       

Hence,

>> exist(lines{1}, 'dir')
ans =
     0

should do the trick.