MATLAB實例:二維高斯分佈圖

MATLAB實例:二維高斯分佈圖

做者:凱魯嘎吉 - 博客園 http://www.cnblogs.com/kailugaji/html

更多請看:隨筆分類 - MATLAB做圖函數

問題描述:用MATLAB在一張圖上同時畫出二維高斯散點圖與分佈圖。spa

數據來源:MATLAB高斯混合數據的生成 將二維數據保存爲gauss_data.txt。htm

前期工做:blog

1. MATLAB程序

clear
clc
% Author:  凱魯嘎吉 - 博客園 http://www.cnblogs.com/kailugaji/
%% 加載數據
data_load=dlmread('./gauss_data.txt');
% 每一類
data_1=data_load(data_load(:, end)==1, :);
data_2=data_load(data_load(:, end)==2, :);
data_3=data_load(data_load(:, end)==3, :);
data_4=data_load(data_load(:, end)==4, :);
data_5=data_load(data_load(:, end)==5, :);
%% 空間座標範圍
x1=-8:0.1:8;
x2=-10:0.1:8;
[X1, X2]=meshgrid(x1, x2);
X=[X1(:) X2(:)];

%第一類數據
mu1=[0 0]; % 均值
S1=[1 0;0 1]; % 協方差
%第二類數據
mu2=[4 4];
S2=[2 -1;-1 2];
%第三類數據
mu3=[-4 4];
S3=[2 1;1 2];
%第四類數據
mu4=[-4 -4];
S4=[2 -1;-1 2];
%第五類數據
mu5=[4 -4];
S5=[2 1;1 2];

%% 高斯機率密度函數
% 份量1
y_1=mvnpdf(X, mu1, S1);
y_1=reshape(y_1, length(x2), length(x1));
% 份量2
y_2=mvnpdf(X, mu2, S2);
y_2=reshape(y_2, length(x2), length(x1));
% 份量3
y_3=mvnpdf(X, mu3, S3);
y_3=reshape(y_3, length(x2), length(x1));
% 份量4
y_4=mvnpdf(X, mu4, S4);
y_4=reshape(y_4, length(x2), length(x1));
% 份量5
y_5=mvnpdf(X, mu5, S5);
y_5=reshape(y_5, length(x2), length(x1));
%% 做圖
figure(1)
contour(x1, x2, y_1);
hold on
contour(x1, x2, y_2);
contour(x1, x2, y_3);
contour(x1, x2, y_4);
contour(x1, x2, y_5);
xlabel('X');
ylabel('Y');
plot(data_1(:, 1), data_1(:, 2), 'b.', 'MarkerSize',10 );
hold on
plot(data_2(:, 1), data_2(:, 2), 'r^', 'MarkerSize',4, 'MarkerFaceColor','r');
plot(data_3(:, 1), data_3(:, 2), 'ko', 'MarkerSize',4, 'MarkerFaceColor','g');
plot(data_4(:, 1), data_4(:, 2), 'rp', 'MarkerSize',4, 'MarkerFaceColor','y');
plot(data_5(:, 1), data_5(:, 2), 'mh', 'MarkerSize',4, 'MarkerFaceColor','m');
saveas(gcf,sprintf('2D_Gauss_PDF.jpg'),'bmp'); %保存圖片

2. 結果

相關文章
相關標籤/搜索