tony danza
tony danza

Reputation: 306

matlab array assignment

I'm trying to save all the files in a directory as an array of strings, like this:

files = {'hello.gdf'; 'hello2.gdf'...; ... 'etc.gdf'}

Since I have many directories, I want to do this automatically. This is my code:

gdffiles = dir(fullfile('D:', 'subject', '01', '*.gdf'))
for i=1:size(gdffiles)
    files(i) = gdffiles(i).name;
end

I want to assign to files the name of the gdf files found, but I get this message:

??? Subscripted assignment dimension mismatch.

Error in ==> getFiles at 3 files(i) = gdffiles(i).name;

What am I doing wrong? Thanks!

Upvotes: 2

Views: 363

Answers (3)

Kiran
Kiran

Reputation: 8528

Have you tried this :

ListOfAllFiles = ls('*.gif')

Hope it helps

Upvotes: 0

Shai
Shai

Reputation: 114786

The reason for error:

You try to assign files in the i-th place a string (char array) gdffiles(i).name. However, you are using an array-element assignment (round parenthesis ()). Therefore, you get an error: You can only assign a single char using files(i).

Possible solutions:

  1. You should assign to files using curly braces - since files is a cell array:

    files{i} = gdffiles(i).name;
    
  2. You can achieve the same result without the loop by:

    files = { gdffiles(:).name };
    

Upvotes: 1

Sameh K. Mohamed
Sameh K. Mohamed

Reputation: 2333

Check this solution

path       = fullfile('D:', 'subject', '01', '*.gdf');
files      = dir(path);
files      = struct2cell(files);
files      = files( 1, 1:end );

Upvotes: 1

Related Questions