How to overwrite matrix in txt file with another matrix?
1 次查看(过去 30 天)
显示 更早的评论
I would like to replace the matrix with the title "//Event" with the variable "Events". My initial solution was to import the txt file and make separated tables so I could overwrite them. Therefore, I tried the following solution https://nl.mathworks.com/matlabcentral/answers/784276-import-several-tables-from-one-txt-file-in-matlab?s_tid=srchtitle with the code below.
var = load(Events.mat);
str = fileread('temp.txt');
tkn = regexp(str,'^/[^\n]([^;]*)([^/]*)','lineanchors','tokens');
I would like to detect with the code above the following tables:
First table named "Title" containing the string
Network defintion and parameters
Second table named "Parameters" with header and numbers:
nrTimePeriods LengthTim LTimeStep ScaleFlow ScaleCap ScaleSpeed DemandPar %header
21 900 10 1.14 1.00 1.00 1 %number
Third table named "Links" with header and numbers:
linknr nettype length nrlanes satflow speed type CTR nrSG Signal(s) nrCL ConfLinks %header
(m) (veh/hr) (km/hr)
1 0 653.8 5 25000 60 0 %number
2 0 580.6 5 25000 50 0 %number
3 0 271.7 5 25000 60 0 %number
4 0 708.5 5 25000 50 0 %number
5 0 496.2 5 25000 60 0 %number
Fourth table named "Events" with header and numbers:
begintime endtime linknr nrlanes satflow vfree type %header
(%) (%)
0 18900 2150 -4 0 100 2 %number
0 18900 2151 -3 0 100 2
0 18900 2149 -3 0 100 2
0 18900 379 -3 0 100 2
0 18900 358 -3 0 100 2
0 18900 349 -3 0 100 2
0 18900 2143 -3 0 100 2
0 18900 2144 -3 0 100 2
2 个评论
Jan
2023-2-24
Please explain, why you think, that this is not matching. Share this important information with us. Otherwise it is hard to guess, what you call "better".
回答(1 个)
Stephen23
2023-2-27
Assuming that the //Events block always occurs last in the text file. Lets start by looking at the content of the two files:
type temp.txt
S = load('Events.mat');
M = S.Events
Now we replace the last data block with that numeric matrix:
L = readlines('temp.txt');
X = find(strncmp(L,';',1),1,'last');
[fid,msg] = fopen('temp_new.txt','wt');
assert(fid>0,msg)
fprintf(fid,'%s\n',L{1:X});
fprintf(fid,'%6g%11g%10g%8g%6g%10g%7g\n',M.');
fclose(fid);
and now lets check the content of the new file:
type temp_new.txt
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!