将每个点分配给它在 Matlab 中最近的中心
Assign each point with it's nearest center in Matlab
我有 100 个点保存在一个矩阵中,3 个中心保存在另一个矩阵中。我想在 Matlab 中为每个点分配最近的中心,并为每个中心创建 3 个组。
例如:
centers = [1,12];
points = [2,3,4,15,18,20];
我想得到 2 个组作为输出:
group1 = [1,2,3,4];
group2 = [12,15,18,20];
两个点和中心具有相同的维度并且距离是Euclidean.Every行代表一个点。
Matlab 中是否有这样的函数?
您想计算每个点到每个中心的距离,然后找出哪个中心离每个点最近。在 1D 中这很简单:
centers = [1,12];
points = [2,3,4,15,18,20];
dist = abs(points - centers.'); % we use implicit singleton expansion here
[~,group] = min(dist,[],1); % returns group = [1,1,1,2,2,2]
请注意,dist
是一个二维矩阵。 dist(i,j)
是 centers(i)
到 points(j)
的距离。输出 group
表示对于每个点,哪个中心最近。
在 2 维或更多维中,这稍微复杂一些,因为 centers
和 points
是二维矩阵,我们需要一个中间 3D 数组来计算欧氏距离:
centers = [0,1,1,0;...
0,0,1,1]; % centers(:,i) is the coordinates for center i
points = rand(2,12); % 12 points in 2D
dist = reshape(points,2,1,[]) - centers; % this is a 3D array
dist = sqrt(sum(dist.^2,1)); % in very new versions of MATLAB do vecnorm(dist,2,1)
dist = squeeze(dist); % removes the first dimension
[~,group] = min(dist,[],1);
上面的代码假定 points
和 centers
的每一列都是一个坐标。如果矩阵的方向相反,每行一个坐标,代码将如下所示:
centers = [0,0;1,0;1,1;0,1]; % centers(i,:) is the coordinates for center i
points = rand(12,2); % 12 points in 2D
dist = reshape(points,1,[],2) - reshape(centers,[],1,2);
dist = sqrt(sum(dist.^2,3)); % in very new versions of MATLAB do vecnorm(dist,2,3)
[~,group] = min(dist,[],1);
我有 100 个点保存在一个矩阵中,3 个中心保存在另一个矩阵中。我想在 Matlab 中为每个点分配最近的中心,并为每个中心创建 3 个组。
例如:
centers = [1,12];
points = [2,3,4,15,18,20];
我想得到 2 个组作为输出:
group1 = [1,2,3,4];
group2 = [12,15,18,20];
两个点和中心具有相同的维度并且距离是Euclidean.Every行代表一个点。
Matlab 中是否有这样的函数?
您想计算每个点到每个中心的距离,然后找出哪个中心离每个点最近。在 1D 中这很简单:
centers = [1,12];
points = [2,3,4,15,18,20];
dist = abs(points - centers.'); % we use implicit singleton expansion here
[~,group] = min(dist,[],1); % returns group = [1,1,1,2,2,2]
请注意,dist
是一个二维矩阵。 dist(i,j)
是 centers(i)
到 points(j)
的距离。输出 group
表示对于每个点,哪个中心最近。
在 2 维或更多维中,这稍微复杂一些,因为 centers
和 points
是二维矩阵,我们需要一个中间 3D 数组来计算欧氏距离:
centers = [0,1,1,0;...
0,0,1,1]; % centers(:,i) is the coordinates for center i
points = rand(2,12); % 12 points in 2D
dist = reshape(points,2,1,[]) - centers; % this is a 3D array
dist = sqrt(sum(dist.^2,1)); % in very new versions of MATLAB do vecnorm(dist,2,1)
dist = squeeze(dist); % removes the first dimension
[~,group] = min(dist,[],1);
上面的代码假定 points
和 centers
的每一列都是一个坐标。如果矩阵的方向相反,每行一个坐标,代码将如下所示:
centers = [0,0;1,0;1,1;0,1]; % centers(i,:) is the coordinates for center i
points = rand(12,2); % 12 points in 2D
dist = reshape(points,1,[],2) - reshape(centers,[],1,2);
dist = sqrt(sum(dist.^2,3)); % in very new versions of MATLAB do vecnorm(dist,2,3)
[~,group] = min(dist,[],1);