Use system function with parfor
3 次查看(过去 30 天)
显示 更早的评论
I'm generating input files to C code from matlab and collecting output from C code into matlab for further processing through .txt files. In between writing & reading "system", matlab builtin
function
will be called to run C binary file as shown below. I'm unable to use "parfor" in place of "for" loop when I use system function?. What can I do to enable "parfor"?
itrMax = 10000;
StoreResult = zeros(1, itrMax );
for i = 1:itrMax
CINP = randi([0 1], 1, 1000);
fp = fopen("input.txt","w");
fprintf(fp, "%d", CINP);
fclose(fp);
cd cCode
system("./a.out");
cd ../
fp = fopen("output.txt","r");
COUT = fscanf(fp,"%d\n");
fclose(fp)
//FUNCTION Call to process COUT, whose output will be a constant
// OutFlag
StoreResult(1, i) = OutFlag;
end
itrMax = 10000;
StoreResult = zeros(1, itrMax );
for i = 1:itrMax
CINP = randi([0 1], 1, 1000);
fp = fopen("input.txt","w");
fprintf(fp, "%d", CINP);
fclose(fp);
cd cCode
system("./a.out");
cd ../
fp = fopen("output.txt","r");
COUT = fscanf(fp,"%d\n");
fclose(fp);
//FUNCTION Call to process COUT, whose output will be a constant
// OutFlag
StoreResult(1, i) = OutFlag;
end
0 个评论
回答(1 个)
Edric Ellis
2020-5-20
It looks like your executable expects to read from input.txt and write to output.txt. This will not work in parallel because the different workers will clash when the all try to write input.txt. What I suggest is that you modify your program so that it takes the input and output files as command-line arguments, and then do something like this:
parfor i = 1:itrMax
input_fname = sprintf('input_%d.txt', i);
output_fname = sprintf('output_%d.txt', i);
fh = fopen(input_fname, 'w');
% write into fh
fclose(fh);
cmd = sprintf('./a.out %s %s', input_fname, output_fname);
system(cmd);
fh = fopen(output_fname, 'r');
% read from fh
fclose(fh);
% Optional - clean up these files
delete(input_fname);
delete(output_fname);
end
2 个评论
Edric Ellis
2020-5-28
You need to change your C code to read from a file named on the command line, and write to a file named on the command line to match the MATLAB code I posted. These days it's probably easier to write C++ than plain C, start with a tutorial like e.g. https://www.w3schools.com/cpp/default.asp . Basically, you need to modify your C(++) code to do the following:
- Make your main function take argc (number of command-line arguments) and argv (the values of those arguments)
- Use argv[1] as the input file name, argv[2] as the output file name
- Probably simpler to read from the file directly rather than using freopen.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Parallel for-Loops (parfor) 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!