0
votes

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)')
2
You want the program to figure out how many columns there are on it's own? so it's not always 3 columns? Can you show us what you tried so far pls? - Max
no it can be 2 or 3 or 4 or even 10. I ve not tried anything, I have already been struggling 2 hours to understand how to plot a function hahah but I can add my results - Marine Galantin

2 Answers

2
votes

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
1
votes

You can plot everything in one window using this:

fid=fopen('test.txt'); % opening the file
dataPlain=textscan(fid,'%s','Delimiter',''); % reading the data from the file
data=cellfun(@str2num,dataPlain{1},'uni',0); % getting only the numerical data
data=cat(1,data{:}); % formatting
figure; % if you want to plot everything in multiple windows, you can put this command into the for loop, too.
hold on
for ii=2:size(data,2)
    plot(data(:,1),data(:,ii)); % plot the data
end