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
댓글 수: 1
참고 항목
카테고리
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!