假如我们有多组txt格式的数据:
其数据格式是这样的:
想要批量读取这些数据,并把他们画在一张图上,该怎么操作呢?
之前有分享load函数的版本,本期进一步分享适用性更强的readtable函数的实现方法。
首先,通过‘dir’命令列出所需路径下所有txt文件:
file_read=dir('D:\no_low-high_outliers\*.txt');
然后,利用‘readtable’命令读取数据,并初始化参数:
data = readtable(strcat('D:\no_low-high_outliers\',filenames{ii}));
x = data{:,1};
y = data{:,2};
z = data{:,3};
A = [x,y,z];
并通过‘scatter3’绘制特征渲染三维散点图:
scatter3(A(:,1),A(:,2),A(:,3),5,A(:,3),'filled')
通过for循环,将读取与可视化结合起来,完整代码如下:
%% 列出文件夹对应内容
file_read=dir('D:\no_low-high_outliers\*.txt');
filenames={file_read.name}';
file_length=length(file_read);
%% 批量读取并可视化数据
% 图片尺寸设置(单位:厘米)
figureUnits = 'centimeters';
figureWidth = 20;
figureHeight = 16;
% 窗口设置
figureHandle = figure('Color','w');
set(gcf, 'Units', figureUnits, 'Position', [0 0 figureWidth figureHeight]);
% 绘制
t = tiledlayout(3,3);
for ii = 1:9
data = readtable(strcat('D:\no_low-high_outliers\',filenames{ii}));
x = data{:,1};
y = data{:,2};
z = data{:,3};
A = [x,y,z];
M = size(A,1);
w = sum(A(:,1:3))/M;
A(:,1:3) = A(:,1:3) - w;
nexttile(ii)
scatter3(A(:,1),A(:,2),A(:,3),5,A(:,3),'filled')
title(filenames{ii})
colormap(TheColor('sci',2068))
end
t.TileSpacing = 'compact';
t.Padding = 'compact';
%% 图片输出
figW = figureWidth;
figH = figureHeight;
set(figureHandle,'PaperUnits',figureUnits);
set(figureHandle,'PaperPosition',[0 0 figW figH]);
fileout = 'test';
print(figureHandle,[fileout,'.png'],'-r300','-dpng');
以上。