• 大小: 1KB
    文件类型: .rar
    金币: 1
    下载: 0 次
    发布日期: 2021-06-19
  • 语言: Matlab
  • 标签: knn算法  

资源简介

通过knn算法,实现WiFi室内定位在matlab环境下的仿真

资源截图

代码片段和文件信息

function result = knn(trainX testY zuobiaoZ k)


% Classify using the Nearest neighbor algorithm
% Inputs:
%  trainX        - Train sample matrix n*d n points each d dimentions
%   testY          - Test sample matrix  N*d  测试样本矩阵
% k        - Number of nearest neighbors 
% Outputs:
% result        - 定位点坐标

%  判断trainX和testY的样本点维数是否相同   
trainX =[34 35 38 40 45 60 62 67;36 34 40 36 42 67 40 65;62 40 48 36 47 67 34 62;38 36 40 45 52 65 70 65; 67 42 50 35 36 70 37 64]
testY = [38 36 39 41 46 61 64 67;70 38 40 55 50 60 55 40;76 33 56 78 40 52 62 35;76 35 23 61 76 35 57 62;87 62 34 47 36 82 21 63];
zuobiaoZ = [0.0 3.0;1.5 3.0; 3.0 3.0;0.0 1.5;3.01.5];
k =3;
zhunqueZ = [0.3 3.0;1.8 1.8;2.0 1.7;0.8 2.9;3.0 2.2]                              %  待定位点的准确坐标
if size(trainX2) ~= size(testY2)                                      
    error (‘trainX and testZ must have same column dimensions !‘)         %  维数d应该相同 在同一个点搜集到的WiFi热点个数相同
end   

%  判断k近邻是否可取
n = size(trainX1);                                                       %  测试样本点个数   参考点的个数必须大于k的个数
if ( n < k)                                
   error(‘You specified more neighbors than existed points.‘)
end                                                                       %  选择的近邻数不大于样本点数

                               
N                   = size(testY 1);                                     %  testZ的行数,即测试集的样本点数
                                                                          %   初始化result矩阵N*1列向量标出testZ的类别


%  按照所选的度量距离,对testY的N个点逐个进行k近邻分类 

                                                        
    for i = 1:N 
        dist            = sum((trainX - ones(n1)*testY(i:)).^22);      %  dist 表示第i个测试点分别与n个训练样本点之间的欧式距离的平方 按行进行求和 dist是个矩阵
        [m indices]    = sort(dist);                                     %  按列进行升序排列   
        histclass       = zuobiaoZ([indices(1:k)]: );                    %  取前k个最短距离对应的点所属的类别,求出k个临近点的坐标
        gd              = sum(histclass);                                 %  k个临近点的坐标相加 
        result(i:)     =gd/k;                                            %  求得定位点的坐标
        x(i)            =result(i1);
        y(i)            =result(i2);
        x1(i)           =zhunqueZ(i1);
        y1(i)           =zhunqueZ(i2);
        
    end
   plot(xy‘square‘‘MarkerSize‘7);
   hold on;
   plot(x1y1‘*‘‘MarkerSize‘7);
       axis([0 3 0 3]);
set(gca‘xtick‘[0:0.2:3]‘ytick‘[0:0.2:3])
    
    

end

 属性            大小     日期    时间   名称
----------- ---------  ---------- -----  ----

     文件       2735  2014-04-17 13:54  knn1.m

----------- ---------  ---------- -----  ----

                 2735                    1


评论

共有 条评论