matlab 点顺时针排序,按顺时针/逆时针顺序对一组三维点进行排序

我无法证明此代码的效率,但它可以工作,你可以根据需要优化它的一部分,我只是不擅长它。

代码在C#中,使用系统集合类和linq

Vector3是一个具有浮点数x,y,z和静态向量数学函数的类

Node是一个名为pos的Vector3变量的类

//Sort nodes with positions in 3d space.

//Assuming the points form a convex shape.

//Assuming points are on a single plain (or close to it).

public List sortVerticies( Vector3 normal, List nodes ) {

Vector3 first = nodes[0].pos;

//Sort by distance from random point to get 2 adjacent points.

List temp = nodes.OrderBy(n => Vector3.Distance(n.pos, first ) ).ToList();

//Create a vector from the 2 adjacent points,

//this will be used to sort all points, except the first, by the angle to this vector.

//Since the shape is convex, angle will not exceed 180 degrees, resulting in a proper sort.

Vector3 refrenceVec = (temp[1].pos - first);

//Sort by angle to reference, but we are still missing the first one.

List results = temp.Skip(1).OrderBy(n => Vector3.Angle(refrenceVec,n.pos - first)).ToList();

//insert the first one, at index 0.

results.Insert(0,nodes[0]);

//Now that it is sorted, we check if we got the direction right, if we didn't we reverse the list.

//We compare the given normal and the cross product of the first 3 point.

//If the magnitude of the sum of the normal and cross product is less than Sqrt(2) then then there is more than 90 between them.

if ( (Vector3.Cross( results[1].pos-results[0].pos, results[2].pos - results[0].pos ).normalized + normal.normalized).magnitude < 1.414f ) {

results.Reverse();

}

return results;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值