nico1510
nico1510

Reputation: 606

Matlab use filepath in variable for textread

I can't make this piece of Code to work

for i = 1:length(names)
 distrfile = ls(strcat('./sample_distributions/sample-distribution_',names{i}(6:end),'*.csv'));
 [threadlength, frequency] = textread(distrfile,'%d %d', 'delimiter', ',');
end

the value I get for distrfile is not empty nor does it reference a file which does not exist. I am also in the correct working directory. If I manually paste the value of distrfile into the Code like

 [threadlength, frequency] = textread('distribution_44_start_50_end_100.csv','%d %d', 'delimiter', ',');

then it is working. I have however no idea what object String or whatever thing is contained in my distrfile variable since I have never worked with matlab. I can only guarantee that the console output of this variable points to a file which DOES exist but I get the following error :

??? Error using ==> textread at 167 File not found.

Error in ==> threadsplot at 65 [threadlength, frequency] = textread(distrfile,'%d %d', 'delimiter', ',');

Upvotes: 0

Views: 309

Answers (1)

gevang
gevang

Reputation: 5014

Seems like the ls command through MATLAB returns a char value with an additional, whitespace in the end of distrfile. Try this (to discard final empty char before reading with textread):

distrfile = distrfile(1:end-1);

This is probably caused by MATLAB involking unix command, inside ls:

[~,file_name] = unix(['ls', file_name]);

You can alternatively use dir, instead of ls, and get the file name using the .name field of the resulting struct:

distrfile = dir(file_name);
[threadlength, frequency] = textread(distrfile.name,'%d %d', 'delimiter', ',');

Note: Other than these, you can pass directly file_name to textread (no need to ls since your outer loop indexes a single, known file_name at each iteration).

Upvotes: 1

Related Questions