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

时间:2018-05-19 12:27:02

标签: matlab matlab-figure

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

2 个答案:

答案 0 :(得分:2)

不需要像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

答案 1 :(得分:1)

您可以使用以下方法在一个窗口中绘制所有内容:

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