You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matlab中点间距离绘图问询:基于10组已知坐标散点图

在MATLAB中可视化散点间距离的方法

嗨,我来帮你搞定在MATLAB里绘制散点间距离的需求!首先咱们先把你的坐标数据整理成MATLAB能识别的格式(你原来的坐标用逗号当小数点,得换成点),创建好坐标矩阵:

% 转换后的坐标矩阵(逗号替换为小数点)
Problem.Points = [
    10 10;
    248.628959661970 66.9462583977501;
    451.638770451973 939.398361884535;
    227.712826026548 18.1775336366957;
    804.449583613070 683.838613746355;
    986.104241895970 783.736480083219;
    29.9919502693899 534.137567882728;
    535.664190667238 885.359450931142;
    87.0772199008924 899.004898906140;
    990 990
];

接下来分几种常见场景来实现:

场景1:绘制所有点对的连线并标注距离

如果想把每两个点之间的距离都可视化出来,可以用这段代码:

% 先绘制原始散点图
scatter(Problem.Points(:,1), Problem.Points(:,2), 'filled', 'MarkerFaceColor', 'b');
hold on;
grid on;
axis equal; % 保持坐标轴比例一致,避免距离视觉失真

% 获取点的总数
n = size(Problem.Points, 1);

% 遍历所有不重复的点对(i<j避免重复绘制同一条线)
for i = 1:n
    for j = i+1:n
        p1 = Problem.Points(i,:);
        p2 = Problem.Points(j,:);
        % 绘制两点间的虚线
        plot([p1(1), p2(1)], [p1(2), p2(2)], 'k--', 'LineWidth', 0.5);
        % 计算欧氏距离
        distance = norm(p1 - p2);
        % 计算连线中点,用来放置距离标注
        mid_point = (p1 + p2)/2;
        % 标注距离(保留2位小数)
        text(mid_point(1), mid_point(2), sprintf('%.2f', distance), ...
             'HorizontalAlignment', 'center', 'FontSize', 8);
    end
end

hold off;
title('散点间距离可视化');
xlabel('X坐标');
ylabel('Y坐标');

代码说明:

  • norm(p1-p2) 是MATLAB里计算欧氏距离的简便写法,和手动计算sqrt((p1(1)-p2(1))^2 + (p1(2)-p2(2))^2)效果完全一样
  • axis equal 非常关键,要是坐标轴比例不一样,连线会看起来歪歪的,距离的视觉感受就不准了
  • 用i<j遍历是为了避免重复绘制同一对点的连线(比如点1到点2和点2到点1是同一条线)

场景2:绘制特定点对的距离

如果只需要关注某几个特定点之间的距离,比如第1个点和第10个点,可以用这段更简洁的代码:

scatter(Problem.Points(:,1), Problem.Points(:,2), 'filled', 'MarkerFaceColor', 'b');
hold on;
grid on;
axis equal;

% 指定要可视化的点对索引(比如第1个和第10个点)
point_idx1 = 1;
point_idx2 = 10;
p1 = Problem.Points(point_idx1,:);
p2 = Problem.Points(point_idx2,:);

% 绘制醒目的红色实线
plot([p1(1), p2(1)], [p1(2), p2(2)], 'r-', 'LineWidth', 1.5);
% 计算距离
distance = norm(p1 - p2);
% 标注距离(可以微调位置避免遮挡)
text((p1(1)+p2(1))/2 + 10, (p1(2)+p2(2))/2 + 10, sprintf('Distance: %.2f', distance), ...
     'Color', 'r', 'FontSize', 10, 'FontWeight', 'bold');

hold off;

额外技巧:生成所有点对的距离矩阵

如果需要得到所有点之间的距离数值(不需要可视化),可以用MATLAB自带的pdist函数快速生成距离矩阵:

% 计算所有点对的欧氏距离,转换成方阵格式
distance_matrix = squareform(pdist(Problem.Points));
% 显示距离矩阵,保留2位小数方便查看
disp(round(distance_matrix, 2));

这个矩阵里,distance_matrix(i,j)就代表第i个点和第j个点之间的距离。

内容的提问来源于stack exchange,提问作者Rogier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:54:49