How to edit a particular row of a particular column of .dat file ?

3 ビュー (過去 30 日間)
Rutvi Thanki
Rutvi Thanki 2016 年 7 月 31 日
コメント済み: Rutvi Thanki 2016 年 7 月 31 日
I am currently working with a code which requires me edit a particular value in a column corresponding to a particular row. Following is an example of
my_dat
Some information about the file
3 !number of months
Jan 45 36 0.05
Feb 55 23 0.0016
Nov 12 7 0.45
I want to change the value 0.0016 in the last column for Feb to say 0.23. I have tried using 'textread' but only reads the first line. I also want matlab to keep the filetype after editing the file.

回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 7 月 31 日
編集済み: Azzi Abdelmalek 2016 年 7 月 31 日
fid=fopen('filename.dat')
d=textscan(fid,'%s %f %f %f')
fclose(fid)
M=cell2mat(d(:,2:4))
%Or
[a,b,c,d]=textread('fic.dat',' %s %f %f %f')
  3 件のコメント
Walter Roberson
Walter Roberson 2016 年 7 月 31 日
Are you sure you used cell2mat(d(:,2:4)) instead of accidentally using cell2mat(d) ?
Rutvi Thanki
Rutvi Thanki 2016 年 7 月 31 日
Yes I did use cell2mat correctly, as mentioned.
Thank you

サインインしてコメントする。


Walter Roberson
Walter Roberson 2016 年 7 月 31 日
fid = fopen('my_dat.dat', 'r');
lines{1} = fgetl(fid);
lines{2} = fgetl(fid);
lines{3} = fgetl(fid);
datacell = textscan(fid, '%s%f%f%f');
fclose(fid);
month_names = datacell{1};
month_col1 = datacell{2};
month_col2 = datacell{3};
month_col3 = datacell{4};
month_col3(2) = 0.23;
And then after that you write the data out to a new file.
There is no way to edit a text file "in place", with the exception of the uncommon case where what you are writing out is exactly the same size as what is already in the file, such as if you wrote 0.2300 to match the size of 0.0016 . Writing text files "in place" is tricky.
There are some other approaches that can be used for the case where you know the exact string you need to substitute for.
  1 件のコメント
Rutvi Thanki
Rutvi Thanki 2016 年 7 月 31 日
Thanks a lot for your reply.
Well I see your approach is good but this was only an example, I have a data file which has 4 columns but about 100 rows. Can you suggest a better way where I might not have to introduce 100 new variables.
Thanks

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeWorkspace Variables and MAT Files についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by