Ocean Blue
Ocean Blue

Reputation: 33

Including variable in file directory in matlab ..?

I want to access several sequenced folders

Example :

[ndata, text, alldata] = xlsread(' D: \ folder \ 1 \ file ' ) ;
[ndata, text, alldata] = xlsread(' D: \ folder \ 2 \ file ' ) ;
[ndata, text, alldata] = xlsread(' D: \ folder \ 3 \ file ' ) ;
[ndata, text, alldata] = xlsread(' D: \ folder \ 4 \ file ' ) ;

Could I replace 1,2,3and 4 by variable i .. How could the directory be written here ?!

Please need any recommendation !

Upvotes: 1

Views: 4077

Answers (4)

tmpearce
tmpearce

Reputation: 12693

[ndata, text, alldata] = xlsread([' D:/folder/' num2str(i) '/file ' ]) ;

Upvotes: 2

rubenvb
rubenvb

Reputation: 76529

Just use forward slashes, that works everywhere.

Don't make things harder than they should be.

Upvotes: 1

PearsonArtPhoto
PearsonArtPhoto

Reputation: 39698

Yes, you can. Use the sprintf() command.

i=1;
[ndata, text, alldata] = xlsread(sprintf('D:\\folder\\%i\\file',i))

To make sure this is working right, change the sprintf to a fprintf, and make sure the file exists.

>> i=1;
>> fprintf('D:\\folder\\%i\\file',i)
D:\folder\1\file
>> ls D:\folder\1\file

Upvotes: 0

Pursuit
Pursuit

Reputation: 12345

The fullfile command is meant for this purpose:

xlsread(fullfile('D:','folder', sprintf('%d',i) , 'file'));

The fullfile function takes care of OS-specific file separator and insuring only one file separator is used per folder division. (i.e. strcmp(fullfile('a','b') equals fullfile('a/','/b'))

Upvotes: 2

Related Questions