matlab meanshift

本文介绍了一个使用MATLAB实现的简单MeanShift聚类算法。该算法通过随机生成数据点并应用MeanShift迭代过程来寻找数据集中的聚类中心。通过可视化结果可以直观地看到聚类效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用MATLAB 编写的meanshift 寻找聚类中心的程序 有些简陋

%% mean shift
%% 产生随机点
x1 = 30 + sqrt(9) * randn(1,100);
y1 = 30 +sqrt(9) * randn(1,100);

x2 =20+sqrt(7) * randn(1,100);
y2 =20+sqrt(7) * randn(1,100);

x3 =10+sqrt(6) * randn(1,100);
y3 =40+sqrt(6) * randn(1,100);

x=[x1 x2 x3];
y=[y1 y2 y3];

h =5;
pointx =[x(1),y(1)];
points=[x' y'];
%% 
%% 
ddd =size(points);
centers=zeros(10,2);
count =1;
for i=1:ddd(1);
    pointx =points(i,:);
    flag=0;
    while(1)
     [number,mh]=FindPoint(pointx,points,h);%返回漂移向量mh。
      if sqrt(mh(1)^2+mh(2)^2)<0.001 
      break;
      end
      pointx=pointx+mh;
    end
    if count==1
       tempcenter=centers(count,:); 
    else
       tempcenter=centers(count-1,:); 
    end
    
    if sqrt((pointx(1)-tempcenter(1))^2+(pointx(2)-tempcenter(2))^2)>5
        for ii=1:count
            tep =centers(ii,:);
            if sqrt((tep(1)-pointx(1))^2+(tep(2)-pointx(2))^2)<1
                flag=1;
                break;
            end
        end
        if flag==0
        centers(count,:)=pointx;
        count=count+1;
        end
    end
end

scatter(x,y,3,'filled');
axis([0 50 0 50]);
hold on
scatter(centers(:,1),centers(:,2),5,[1 0 0],'filled');



函数
FindPoint求出均值漂移向量
function [ number,mh] = FindPoint( pointx,points,radis )
%FINDPOINT Summary of this function goes here
%   Detailed explanation goes here
    a=size(points);
    num=0;
    sum=[0,0];
    total =a(1);
    for i=1:total
        temppoint =points(i,:);
        r=sqrt((pointx(1)-temppoint(1))*(pointx(1)-temppoint(1))+(pointx(2)-temppoint(2))*(pointx(2)-temppoint(2)));
        if(r<=radis)
            num=num+1;
            sum=sum+[temppoint(1)-pointx(1),temppoint(2)-pointx(2)];
        end
    end
    number=num;
    mh=sum/num;
end



效果图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值