How to read strings line-by-line and pass them as inputs to a program

3 次查看(过去 30 天)
I have written a code (say run.m) that takes the path of the directory of my data-set as a command line input (there is no other input required). I need to process many data-sets in batch, which sit in different directories. For that I have written a text file (say datasetpaths.txt), each line of which is a path to a directory (hence each line in my textfile string, obviously). Suppose I have 10 such lines (paths) for 10 data-sets and my program (run.m) has to run for all of them. How do I read the textfile and pass the individual lines as command-line inputs to my program ?
  1 个评论
TP Das
TP Das 2015-2-27
编辑:Guillaume 2015-2-27
Dear Guillaume, Thank you for caring to respond. This solution doesn't work, because in my datasetpaths.txt file there are multiple lines (i.e. multiple paths) while the cellstr(fileread('datasetpaths.txt')) command makes it read as a 1X1 matrix. I need to read each line separately and pass them to my program run.m. The 'datasetpaths.txt' is like as follows:
I:/datafolder/instrument_1/23Jan2015
I:/datafolder/instrument_5/23Jan2015
I:/datafolder/instrument_1/27Jan2015
I:/datafolder/instrument_2/29Jan2015
Here there are 4 lines, i.e. 4 paths. First my program should run the code as run('I:/datafolder/instrument_1/23Jan2015') Then run('I:/datafolder/instrument_5/23Jan2015') as so on.

请先登录,再进行评论。

回答(1 个)

Guillaume
Guillaume 2015-2-26
编辑:Guillaume 2015-2-26
dirpaths = cellstr(fileread('datasetpaths.txt'));
for dirpath = dirpaths
run(dirpath{1}); %note that run is not a very descriptive function name
end
  2 个评论
Guillaume
Guillaume 2015-2-27
TP Das comment copied here: Dear Guillaume, Thank you for caring to respond. This solution doesn't work, because in my datasetpaths.txt file there are multiple lines (i.e. multiple paths) while the cellstr(fileread('datasetpaths.txt')) command makes it read as a 1X1 matrix. I need to read each line separately and pass them to my program run.m. The 'datasetpaths.txt' is like as follows:
I:/datafolder/instrument_1/23Jan2015
I:/datafolder/instrument_5/23Jan2015
I:/datafolder/instrument_1/27Jan2015
I:/datafolder/instrument_2/29Jan2015
Here there are 4 lines, i.e. 4 paths. First my program should run the code as run('I:/datafolder/instrument_1/23Jan2015') Then run('I:/datafolder/instrument_5/23Jan2015') as so on.
Guillaume
Guillaume 2015-2-27
Sorry, I forgot that fileread does not return a char array but just a single string with '\n' as line seperator. As a result, cellstr does not split anything. Still, the principle is the same, use strsplit instead:
dirpaths = strsplit(fileread('datasetpaths.txt'), '\n');
for dirpath = dirpaths
run(dirpath{1}); %note that run is not a very descriptive function name
end

请先登录,再进行评论。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by