Average of values from a column/ Skip lines (textscan)

。_饼干妹妹 提交于 2019-12-11 06:17:18

问题


I have a .txt file which looks like this:

******text*******
(30 lines containing text and *)
******text*******

a b c
a b c
a b c
a b c
a b c
a b c
a b c

(I'm creating a plot with a as x and b and c as y1 and y2)

How do I skip those 30 lines with textscan? I had this but it didn't work:

[x y1 y2] = textscan('file_name.txt', '%f %f %f', 30);

And more: how to I make the average of the values of third column?


回答1:


How do I skip certain lines from being processed?

You have a few options regarding line skipping:

  • If the number of lines are always static, and always in the beginning of the file:

    Pass HeaderLines with a value of N, with N being the numbers you'd like not to process.

    [x y1 y2] = textscan ('file_name.txt', '%f %f %f', 'HeaderLines', 30 + 2);

  • If all lines start with the same character string

    *Pass CommentStyle with a value of ABC where ABC is the comment style.

    If all lines to skip start with *, pass '*' to textscan.

    [x y1 y2] = textscan ('file_name.txt', '%f %f %f', 'CommentStyle', '*');


How do I get the average of some array?

To get the average of some array, use mean:

y1_average = mean (y1);

Documentation of textscan:

  • Read formatted data from text file or string - MATLAB

Documentation of mean

  • Average or mean value of array - MATLAB



回答2:


If you know how many lines to skip use HeaderLines parameter in TEXTSCAN function:

[x y1 y2] = textscan('file_name.txt', '%f %f %f', 'HeaderLines',30);

When you use integer argument after the formatting string, it means you want to apply the formatting string this number of times (number of lines to read in your case). So it's opposite to what you want.

To get the average use MEAN function:

y2_avg = mean(y2);



来源:https://stackoverflow.com/questions/8617405/average-of-values-from-a-column-skip-lines-textscan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!