I have a text file with 10 lines and 5 columns. I need to write a value (zero or one) at the end of each row, that is, in the last column of each row. How can i do this?
5 ビュー (過去 30 日間)
古いコメントを表示
I have a text file with 10 lines and 5 columns. I need to write a value (zero or one) at the end of each row, that is, in the last column of each row. How can i do this? I'm trying to write in a specific row and column. I was trying to use this: dlmwrite(filename,M,delimiter,row,col)
My file:
1.6 0.81 7.4 -4.7 -3.6
-7.6 8.8 2.9 -0.41 2.8
0.89 2.9 0.88 4.4 0.45
9.9 -5.6 -7.9 -7.8 -8.7
-1.9 -1 -2.7 5.3 2.6
5.4 8.7 9.5 -6.2 -7.2
3.9 -8.1 0.51 0.61 7.2
-0.3 -2.1 3.4 4.8 0.4
-3 -7 1.7 -4.8 -9.1
5.1 -5.1 -1.2 3.8 -2.8
0 件のコメント
回答 (1 件)
Chris
2022 年 10 月 31 日
編集済み: Chris
2022 年 10 月 31 日
dlmwrite is deprecated, though you could use it in a similar fashion as below:
fname = 'filename.txt';
outname = 'out.txt';
M = readmatrix(fname);
M(:,end+1) = randi(2,10,1)-1
writematrix(M,outname,'delimiter','space');
If you want integer formatting for the ones/zeros, you could use tables:
M = readtable(fname);
endbits = randi(2,10,1)-1;
M(:,end+1) = table(endbits)
writetable(M,outname,'WriteVariableNames',false,'delimiter','space');
Edit: If you want to change one line at a time, one option is to use a cell array.
fname = 'filename.txt';
M = readcell(fname);
% Fix missing
mask = cellfun(@ismissing, M);
M(mask) = {[]};
% Write a value
M{3,end+1} = 1
% Write the file
writecell(M,fname,'delimiter','space');
The output:
1.6 0.81 7.4 -4.7 -3.6
-7.6 8.8 2.9 -0.41 2.8
0.89 2.9 0.88 4.4 0.45 1
9.9 -5.6 -7.9 -7.8 -8.7
-1.9 -1 -2.7 5.3 2.6
5.4 8.7 9.5 -6.2 -7.2
3.9 -8.1 0.51 0.61 7.2
-0.3 -2.1 3.4 4.8 0.4
-3 -7 1.7 -4.8 -9.1
5.1 -5.1 -1.2 3.8 -2.8
4 件のコメント
Chris
2022 年 11 月 1 日
A 30,000 x 6 cell array takes up 20 MB in memory, which is small potatoes when you're working with GB of RAM.
Writing such a file to my SSD takes ~9 s, and reading it takes 2. An old drive might be a bit slower, but I think the speed is mostly limited by whatever the writecell function is doing in the background.
A typical program flow would be to load the file into Matlab at the start of your program and work on it in memory, then write it out ("save" the file) when you're ready to close the program. Working in RAM is lightning fast compared to reading/writing to hard disk. If you can deal with the long read/write times at the beginning and end, that's what I would do (perhaps display 'Please wait...' while loading/saving).
If, for some reason, you still want to write bits randomly to the hard drive and not keep the file in memory, then we're in an area I don't know much about. Off the top of my head, a tall array might be appropriate in that case. Or a database.
参考
カテゴリ
Help Center および File Exchange で Low-Level File I/O についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!