如何读取文本文件中的信息以绘制数据?软件

How to read information in text file in order to plot the data ? MATLAB

我开始使用 matlab,我正在搜索如何获取写入 .txt 文件的信息(格式如下:

% 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

然后使用 matlab 将它们绘制成不同的图形。该程序必须检查写入了多少列(此处为 1 + 2 ),取第一列作为横坐标,接下来的几列用于绘制 y 轴。各列之间用一个空格 (" ") 分隔。

我的问题是我不知道如何知道有多少列,然后进行for循环。我很想知道如何在一个屏幕上以及在不同屏幕上为每一列绘制所有内容。

到目前为止,我已经完成了:

 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)')

您可以使用以下方法 window 将所有内容绘制成一个图:

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

无需使用 fopentextscan 等低级例程来读取此类常规数据,尤其是在您不知道有多少列的情况下。也不要使用循环来绘制数据,除非你真的希望它们在单独的图形上,这对于这个数据来说似乎不寻常

使用readtable读取文件,并在同一轴上绘制所有列:

data = readtable('test.txt');
plot(data{:,1},data{:,2:end});

或者如果您确实想要单独的数字:

for idx = 1:width(data)-1
   figure(idx)
   plot(data{:,1},data{:,idx+1});
end