How can I add a cell array to an open file?

조회 수: 1 (최근 30일)
Daniel Albrecht
Daniel Albrecht 2023년 7월 6일
답변: Angelo Yeo 2023년 7월 6일
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);

채택된 답변

Angelo Yeo
Angelo Yeo 2023년 7월 6일
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개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by