フィルターのクリア

How can I extract the last rows of specific columns of a text file

4 ビュー (過去 30 日間)
ND
ND 2015 年 10 月 19 日
編集済み: ND 2015 年 10 月 25 日
Please, I have a text file contains three columns I need to extract the last rows of the third and forth columns only and write them into a text file. for example, from the text file attached the result needs to be written in a text file. it should return:
1.87 36
157 35
1.88 37
1.36 48
1.73 78
1.99 100
Many thanks
  2 件のコメント
Jan
Jan 2015 年 10 月 19 日
There is no attached file.
ND
ND 2015 年 10 月 19 日
編集済み: ND 2015 年 10 月 19 日
Sorry this is the file, Thanks

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

採用された回答

Thorsten
Thorsten 2015 年 10 月 21 日
編集済み: Thorsten 2015 年 10 月 21 日
Read the data from file, ignoring 1 header line:
data = cell2mat(textscan(fopen('a.txt'), '%f%f%f', 'headerlines', 1));
Find the last position for each sequence in column 2. The last position is the position where the data changes, i.e., where the difference is > 0. Add 1 to the end get the last position for the last sequence:
idx = find([diff(data(:,2)); 1] > 0);
Now we have the position of the last entry of each sequence in ind. Since we want the last n elements of a sequence, we use the entry x minus n+1, so x -2 in case of n = 3. For the i'th sequence, we want to extract data(ind(i)-2:ind(i), 3). Instead of using a for-loop, we use arrayfun to work on the ind array:
d3 = arrayfun(@(x) (data(x-2:x,3)), idx, 'UniformOutput', false);
The final step is to write the numbers to a file:
dlmwrite('b.txt', d3)
  2 件のコメント
ND
ND 2015 年 10 月 21 日
編集済み: ND 2015 年 10 月 21 日
Many thanks Thorsten Sorry, what about if I do not have headers ,( just data)?
Thorsten
Thorsten 2015 年 10 月 21 日
Just don't skip the ", 'headerlines', 1" part.

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

その他の回答 (1 件)

TastyPastry
TastyPastry 2015 年 10 月 19 日
Open the file
fid = fopen('your file name.txt');
Skip the header
fgetl(fid);
Use textscan()
myOutput = textscan(fid,'%d %d %d');
It will return a cell array containing all the numerical data, just ignore the first two columns.
  1 件のコメント
ND
ND 2015 年 10 月 20 日
編集済み: ND 2015 年 10 月 21 日
Sorry that is not what I need. For example, a text file has the following:
Bar No increment No Variable
1 1 0
2 1 3
1 2 4
2 2 5
1 2 6
2 2 9
I need to extract just the last variable values(column 3) of each increment
Returns one column written in a text file as :
0
3
6
9

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

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by