I'm beginning in matlab and I'm searching how to get the information that are written in a .txt file (that would be in this format :
% t, x1, x2
0 1 1
0.01 1.01902 1.0195
0.02 1.03706 1.0376
0.03 1.05411 1.0511
0.04 1.07019 1.0719
0.05 1.08529 1.0829
0.06 1.0994 1.094
0.07 1.11253 1.1153
0.08 1.12468 1.128
0.09 1.13586 1.136
0.1 1.14604 1.14615
in order to then plot them in different figures using matlab. The program has to check how many columns are written (here 1 + 2 ), take the first one for the abscises, and the next ones for ploting the y-axis. The columns are separated with one blank ( " " ).
My problem is that I don't know how to know how many columns there is, and then do the for-loop. I'm interested in knowing how to plot everything on one screen and on different screens for each column.
by now i ve done this :
data = load('test.txt');
t = data(:, 1);
ta = data(:, 2);
x = 0: pi/10: pi;
y = sin(x)/ 100 +1;
figure('Name','Name Hello1','NumberTitle','off', ...
'units','normalized','outerposition',[0.01 0.1 0.5 0.7]);
h1 = figure(1);
plot(t, ta, 'bx', 'LineWidth',2)
title('2-D Line Plot')
xlabel('x')
ylabel('cos(5x)')
figure('Name','Name hello 2 2','NumberTitle','off',...
'units','normalized','outerposition',[0.02 0.07 0.5 0.7]);
h2 = figure(2);
plot(x, y , 'LineWidth',2)
title('2-D Line Plot')
xlabel('x')
ylabel('cos(5x)')
There's no need to use low level routines like fopen
and textscan
to read regular data like this, especially if you don't know how many columns there are. Nor to use a loop to plot the data, unless you really want them to be on separate figures, which for this data would seem unusual
Use readtable
to read the file, and plot all the columns in the same axis:
data = readtable('test.txt');
plot(data{:,1},data{:,2:end});
Or if you do want separate figures:
for idx = 1:width(data)-1
figure(idx)
plot(data{:,1},data{:,idx+1});
end