How to write to in MATLAB, translated from R
13 views (last 30 days)
Show older comments
I have the following R code of 'string replace and write to' but it could not be recognized when running in terminal. So need to write to MATLAB code.
input: subj001_script.m containing character of subj001
output_expected: output/subj001_script.m containing subj001
output/subj002_script.m containing subj002
output/subj003_script.m containing subj003
output/subj004_script.m containing subj004
%% array of ids
ids=data.frame("V1"=c("subj001", "subj002", "subj003", "subj004"))
%% sample script for subj001
txt2 <- readLines("subj001_script.m")
%% replace subj001 with ids and write to
for (i in ids$V1){
writeLines(gsub("subj001", i, txt2), paste0("output/", i, "_script.m"))
}
What I did is so far is below and I don't know if there is a function that can "paste0" for naming in MATLAB code?
line='subj001'+"\n"+'subj002'+"\n"+"subj003"+'\n'+'subj004';
file= compose(line);
ids=strsplit(file);
txt2=fileread("subj001_script.m");
for i =ids
fprintf(strrep(txt2,"subj001", i), ???? ("output/", i, "_script.m"))
end
1 Comment
Image Analyst
on 2 Jun 2022
Edited: Image Analyst
on 2 Jun 2022
Why do you need to call strsplit()? The strrep should be able to work on "file" (the whole, entire file contents).
Attach "list.txt" if you need any more help, after reading this:
Answers (3)
the cyclist
on 2 Jun 2022
String concatenation in MATLAB can be done as "addition":
i = 7;
"output/" + i + "_script.m"
0 Comments
qi zeng
on 2 Jun 2022
1 Comment
the cyclist
on 3 Jun 2022
I couldn't figure out what either your R code or your MATLAB attempt was doing, which is why I answered only that small question about paste0().
Image Analyst
on 3 Jun 2022
Your post was so confusing that I don't know what pattern should be replaced by what other desired pattern. But it might go something like this:
% Read input file.
inputLines = readlines(inputFileName);
numLines = numel(inputLines)
outputLines = cell(numLines, 1);
% Loop over every line replacing *something* with *something else* -
% whatever those might be.
for k = 1 : numel(inputLines)
% Replace inputPattern withdesiredPattern
outputLines{k} = strrep(inputLines{k}, inputPattern, desiredPattern);
end
% Write output file.
writelines(outputLines, outputFileName);
Make the proper adaptations like defining the input and output patterns.
0 Comments
See Also
Categories
Find more on Annotations 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!