Plot data from data file with unknown number of columns
2 views (last 30 days)
Show older comments
Hi to every one. I am a novice to MATLAB. I am trying to plot figures from a data file. The data file is generated using a software. The number of columns is not fixed and can be changed according to requirement. I want to build a script which can read the file and then plot it. Another thing is that I want to put header line as the legends of the plot. I am attaching the data file as well as the plot. Your kind help would be highly appreciated.***
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/192897/image.png)
Time Pop1 Pop2
1.0000000E-08 4.097568E-006 2.211371E-005
2.0000000E-08 3.511726E-006 1.775795E-005
3.0000000E-08 2.828558E-006 1.429533E-005
4.0000000E-08 2.265553E-006 1.154281E-005
5.0000000E-08 1.816197E-006 9.354735E-006
6.0000000E-08 1.458834E-006 7.615319E-006
7.0000000E-08 1.174745E-006 6.232541E-006
8.0000000E-08 9.489138E-007 5.133246E-006
9.0000000E-08 7.693916E-007 4.259290E-006
1.0000000E-07 6.266799E-007 3.564453E-006
Currently, I am using this script, but it is not generating legend with the plot.
clear all;
close all;
clc
A=dlmread('levelspp.dat','', 1, 0);
x=A(:,1);
B=dlmread('levelspd.dat','', 1, 0);
x1=B(:,1);
figure(2)
plot(x,A(:,2:end))
xlabel('Time (s)')
ylabel('Population')
figure(3)
plot(x1,B(:,2:end))
xlabel('Time (s)')
ylabel('Population')
2 Comments
Accepted Answer
KSSV
on 29 Oct 2018
Edited: KSSV
on 29 Oct 2018
YOu need not to know how many columns are present. You can use importdata to load the data.....and you can plot.
A = importdata('data.txt') ;
data = A.data ;
t = data(:,1) ; % time
y = data(:,2:end) ;
plot(t,y)
l = legend ;
l.String = strrep(l.String,'data','Pop')
If you want the number of columns. Use size. size(data) should give you the number of columns.
4 Comments
More Answers (0)
See Also
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!