How to read multiple line data from text file and plot?

24 views (last 30 days)
Hello I have tabular data (series of Y's) in text file and I want to plot this data against X's. Here is my file sample. Name of file is data.txt
1 2 3 4 5 5 4 3 2 1
3 4 5 6 7 7 6 5 4 3
5 6 7 8 9 9 8 7 6 5
10 11 12 13 14 11 10 9 8 7
12 13 14 15 16 13 12 11 10 9
14 15 16 17 18 15 12 13 12 11
16 17 18 19 20 17 14 15 14 13
18 19 20 21 22 19 16 17 16 15
25 26 27 28 29 26 18 19 18 17
27 28 29 30 31 28 20 21 20 19
33 34 35 36 37 34 22 23 22 21
35 36 37 38 39 36 24 25 24 23
37 38 39 40 41 38 26 27 26 25
45 46 47 48 43 40 28 29 28 27
47 48 49 50 45 42 30 31 30 29
These are series of Y's. I create a script to plot them against X's.
clc;
close all;
clear all;
load data.txt
x=1:1:10;
figure();
y=zeros(1,10);
for i=1:1:15
y=data(i,:);
plot(x,y,'k');
axis([0 11 0 75]);
xlabel('X');
ylabel('Y');
pause(0.1);
end
This works for my purpose. However when I checked matlab documentation, I found fscanf() is used to read a file. Which option is better? And if I want to use fscanf, can someone please help me what the code would be? In addition, I would like to get number of lines to read, so I can put them into for loop. Any idea how to get this information as well? Thanks in advance.

Answers (1)

Star Strider
Star Strider on 19 Aug 2014
If load works, use it!
There are a variety of ways to read files in MATLAB depending on the file format, content, and your needs, including fscanf, dlmread, textscan, xlsread, and others.
  2 Comments
A13u34
A13u34 on 19 Aug 2014
I wanted to check fscanf or other file reading option. Also, it will be possible to get number of lines from these commands.
Star Strider
Star Strider on 19 Aug 2014
Only fscanf will provide the number of characters read in. I don’t usually use the input length or row-column options, but csvread and dlmread (and xlsread but it only reads Excel-format files) can control the row and column ranges the functions will read. Some also have various format options to control the number of values read in.
The size of the matrix created from the functions will tell you the number of lines they have read. That is the only way I know of to find and verify that.
I prefer the function form of load, with an output argument. For instance, changing your load call to:
Y = load('data.txt')
will provide you with a structure or variable in Y that will tell you what load imported into your workspace and its size.
If you want to read only a specific number of lines from a file, you can use fgets or fgetl in a for-loop. I rarely use these, so it’s likely best that you experiment with them in your application.

Sign in to comment.

Categories

Find more on Data Import and Export in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!