【问题标题】:Creating a structure point and then calculating distance between two points创建结构点,然后计算两点之间的距离
【发布时间】:2014-11-28 00:14:23
【问题描述】:

我需要一些帮助来确定如何创建结构点。

我需要两个字段 x 和 y,然后我想创建一个函数来计算这两个点之间的距离。

我现在拥有的是:

function [ out ] = pointDist3( pointpair1, pointpair2)
%FUNCTION pointDist3 takes in any two pairs of points and 
% Calling sequence:
%   out = pointDist3(varargin)
%DEFINE VARIABLES
% minargs, maxargs = error checking variables 
% pointpair1 = structure containing fields for point 1: x1 and y1
% pointpair2 = structure containing fields for point 2: x2 and y2
% out = structure containing field distance

%CHECK FOR VALID INPUT
if ~isfield(pointpair1,'x', pointpair2, 'x' ) || ~isfield(pointpair1,'y', pointpair2, 'y')
    error('Input argument does not contain fields "x" and "y" for both points');
else

    out = sqrt((pointpair1.x-pointpair2.x)^2+(pointpair1.y-pointpair2.y)^2);

   end

end

【问题讨论】:

  • 问题是什么?您的代码是否有效?
  • 我正在尝试做这个问题:定义一个包含两个字段x和y的结构点。 x 字段将包含点的 x 位置,y 字段将包含点的 y 位置。然后编写一个函数pointDist3,它接受两个点并返回笛卡尔平面上两个点之间的距离。请务必检查函数中输入参数的数量。

    不,它不起作用,因为它卡在 if 语句中。

  • 我收到此错误“使用 isfield 时出错”“输入参数过多。” '如果 ~isfield(pointpair1,'x', pointpair2, 'x') || 在 pointDist3 (line 28) 中出错~isfield(pointpair1,'y', pointpair2, 'y')'
  • 查看isfield文档,你用错了。

标签: arrays matlab struct cell-array euclidean-distance


【解决方案1】:

感谢大卫的修复!这是工作版本

function [ out ] = pointDist3( pointpair1, pointpair2)
%FUNCTION pointDist3 takes in any two pairs of points and 
% Calling sequence:
%   out = pointDist3(varargin)
%DEFINE VARIABLES
% minargs, maxargs = error checking variables 
% pointpair1 = structure containing fields for point 1: x1 and y1
% pointpair2 = structure containing fields for point 2: x2 and y2
% out = structure containing field distance

%CHECK FOR VALID INPUT
    if ~isfield(pointpair1,'x')|| ~isfield(pointpair2, 'x' ) || ~isfield(pointpair1,'y') || ~isfield(pointpair2, 'y')
        error('Input argument does not contain fields "x" and "y" for both points');
    else

        out = sqrt((pointpair1.x-pointpair2.x)^2+(pointpair1.y-pointpair2.y)^2);
    end 
end

测试者:

   >> pointA.x = 3

pointA = 

    x: 3

>> pointA.y =4

pointA = 

    x: 3
    y: 4

>> pointB.x=4

pointB = 

    x: 4

>> pointB.y=5

pointB = 

    x: 4
    y: 5

>> pointDist3(pointA, pointB)

ans =

    1.4142

【讨论】:

    猜你喜欢
    • 2010-10-30
    • 2011-04-23
    • 2014-11-14
    • 1970-01-01
    • 2017-08-27
    • 2015-08-16
    相关资源
    最近更新 更多