How can I add a cell array to an open file?
2 views (last 30 days)
Show older comments
I'm trying to loop over a template .m file, swap out several lines, and save out a new .m file to run SPM jobs. My code works fine for a single line swap, but the issue is that I need to insert an Nx1 cellstring array into one of the lines. In the example below, "outdir", "cfgfile", and "matfile" are all single strings, but "files" needs to be the Nx1 cell array. I'm not well-practiced in text editing like this, and I haven't been able to find a good solution to add the cell array into the existing template framework. Any help is greatly appreciated!
fi = fopen(script,'r'); % open a script template
fileo = outfile;
fo = fopen(fileo,'w'); % the file to write into
% replace strings in the template to generate script for the scan
while ~feof(fi)
l = fgetl(fi);
if strfind(l,'matlabbatch{1}.spm.tools.snpm.des.OneSampT.P =') == 1
l = ['matlabbatch{1}.spm.tools.snpm.des.OneSampT.P = {''',...
files, '''};'];
end
if strfind(l,'matlabbatch{1}.spm.tools.snpm.des.OneSampT.dir =') == 1
l = ['matlabbatch{1}.spm.tools.snpm.des.OneSampT.dir = ''',...
outdir, ''';'];
end
if strfind(l,'matlabbatch{2}.spm.tools.snpm.cp.snpmcfg =') == 1
l = ['matlabbatch{2}.spm.tools.snpm.cp.snpmcfg = ''',...
cfgfile, ''';'];
end
if strfind(l,'matlabbatch{3}.spm.tools.snpm.inference.SnPMmat =') == 1
l = ['matlabbatch{3}.spm.tools.snpm.inference.SnPMmat = ''',...
matfile, ''';'];
end
fprintf(fo,'%s\n',l);
end
fclose(fi);
fclose(fo);
0 Comments
Accepted Answer
Angelo Yeo
on 6 Jul 2023
Hello Daniel,
I belive learning string type can be very helpful. In recent releases of MATLAB, string overwhelms char types in terms of convenience.
When editing text files, using readlines and writelines is a good idea. Also, if you want to replace a part of texts, you can use replace function. Also, if you want to find a pattern match in string, you can use pattern.
Hope this helps,
Angelo
0 Comments
More Answers (0)
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!