Exporting values from Matlab into a Formatted Text File
信息
此问题已关闭。 请重新打开它进行编辑或回答。
显示 更早的评论
I created a code in MatLab that produces outputs that I want to place into a formatted text file. I placed pound signs in the text file which the values from Matlab would replace. How would I go about coding this?
0 个评论
回答(1 个)
Are Mjaavatten
2018-2-26
编辑:Are Mjaavatten
2018-2-26
Here is one way to do it. Note that I collect all the output values in a cell array of strings.
First, a sample input file, with $ signs:
$ seconds was the first 100 m world record, set in 1891.
The record has been improved several times since then.
The current record of $ seconds was set by $ in $.
Next, the code:
infile = 'word_records.txt';
outfile = 'world records_new.txt';
data = {'10.8','9.572','Usain Bolt','2009'};
fid = fopen(infile);
c = fread(fid); % Read file as binary, keeping line feeds.
fclose(fid);
old = char(c'); % Turn integer array into string
% Split string at $ signs:
r = regexp(old,'\$','split');
% Create new string:
new = '';
start = 1;
if isempty(r{1}) % If text start with $
new = data{1};
start = 2;
end
for k = start:length(r)
new = [new,r{k}];
if k <= length(data)
new = [new,data{k}];
end
end
% write new file:
fid = fopen(outfile,'wt');
fprintf(fid,'%s',new);
fclose(fid);
0 个评论
此问题已关闭。
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!