How Can you redesign this code? Same result but different structure

1 回表示 (過去 30 日間)
Alice Zurock
Alice Zurock 2020 年 3 月 29 日
コメント済み: Alice Zurock 2020 年 3 月 30 日
My Code:
clear
format compact
close all
randn('seed',0)
% Definition of mu's and Sigma
% Mean vectors and covariance matrix
m1=[0 2]'; m2=[0 0]'; S1=[4 1.8; 1.8 1]; S2= [4 1.2; 1.2 1];
% Number of data points
n_points_per_class=5000;
% (i) Data point generation
X=[mvnrnd(m1',S1,n_points_per_class); mvnrnd(m2',S2,n_points_per_class)]';
label=[ones(1,n_points_per_class) 2*ones(1,n_points_per_class)];
[l,p]=size(X);
%Plot the data set
figure; plot(X(1,label==1),X(2,label==1),'.b',X(1,label==2),X(2,label==2),'.r'); axis equal
% (ii) Bayes classification of X
% Estimation of a priori probabilities
P1=n_points_per_class/p;
P2=P1;
% Estimation of pdf's for each data point
for i=1:p
p1(i)=(1/(2*pi*sqrt(det(S1))))*exp(-(X(:,i)-m1)'*inv(S1)*(X(:,i)-m1)/2);
p2(i)=(1/(2*pi*sqrt(det(S2))))*exp(-(X(:,i)-m2)'*inv(S2)*(X(:,i)-m2)/2);
end
% Classification of the data points
for i=1:p
if(P1*p1(i)>P2*p2(i))
class(i)=1;
else
class(i)=2;
end
end
% (iii) Error probability estimation
Pe=0; %Probability of error
for i=1:p
if(class(i)~=label(i))
Pe=Pe+1;
end
end
Pe=Pe/p
  2 件のコメント
Walter Roberson
Walter Roberson 2020 年 3 月 29 日
Questions like that, without explanation of the reason for rewriting, tend to remind me of students who find someone else's code to do a task and want to rewrite it to hide the fact that they copied the solution instead of creating it themselves.
Alice Zurock
Alice Zurock 2020 年 3 月 29 日
編集済み: Alice Zurock 2020 年 3 月 29 日
I will update, btw this is only practice on my side. I want to see different perspective about algorithms to improve my capability.

サインインしてコメントする。

採用された回答

darova
darova 2020 年 3 月 29 日
You can remove some constants from for loop to speed up your code
This part can be shorter and vectorized
% for i=1:p
% if(P1*p1(i)>P2*p2(i))
% class(i)=1;
% else
% class(i)=2;
% end
% end
ix = P1*p1 > P2*p2
class = ix + 2*~ix;
  4 件のコメント
Alice Zurock
Alice Zurock 2020 年 3 月 30 日
編集済み: Alice Zurock 2020 年 3 月 30 日
https://www.mathworks.com/matlabcentral/answers/513886-how-can-you-redesign-this-code-i-want-to-see-different-perspectives
Thanks, could you look and advise me in this link ??
Alice Zurock
Alice Zurock 2020 年 3 月 30 日
https://www.mathworks.com/matlabcentral/answers/513886-how-can-you-redesign-this-code-i-want-to-see-different-perspectives
Thanks, could you look and advise me in this link ??

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by