Reading last lines in a text file

21 visualizzazioni (ultimi 30 giorni)
Hey everyone!
I have a quick question. I want to read the last 100 data from a .txt file. The .txt will update now and then, but I need the last 100.
The file looks like this :
22 40866
18 40867
17 40868
9 40869
81 40868
81 40870
I'm using this code for reading :
fid = fopen('HCl.txt');
A = textscan(fid, '%s %s', 'delimiter', '\t');
fclose(fid);
I want to keep textscan because it reads in a way that I get arrays. A{1,1} and A{1,2}
A{1,1} = [22 18 17 9 81 81]
A{1,2} = [40866 40867 40868 40869 40868 40870 ]
So by reading(let's say) the last 2, I should get :
A{1,1} = [81 81]
A{1,2} = [40868 40870 ]
I found something but it applies only to fscanf which doesn't give out in arrays. It goes something like R = A(end,2:end)
Thank you in advance!

Risposta accettata

Fangjun Jiang
Fangjun Jiang il 22 Nov 2011
Your data are numerical so I think it's better to read them as numerical data.
fid = fopen('HCl.txt','rt');
A = textscan(fid, '%f %f', 'delimiter', '\t','collectoutput',true);
A=A{1};
fclose(fid);
It will give you nx2 matrix where n is the number of lines. Then you can do the following.
n=size(A,1);
if n>100
NewA=A(end-99:end,:);
else
NewA=A;
end
  4 Commenti
Fangjun Jiang
Fangjun Jiang il 23 Nov 2011
Sorry, A is a cell array as it is now in the code. Run A=A{1} or A=cell2mat(A) after the textscan() reading. You'll get a nx2 matrix.
Slobodan Djordjevi?
Slobodan Djordjevi? il 24 Nov 2011
Fangjun Jiang, you are my angel! :)
Thanks man!

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Data Import and Export in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by