【发布时间】:2016-07-30 16:15:35
【问题描述】:
我是 MATLAB 新手,但使用过 javascript 和其他编程语言。
我正在编写一个 MATLAB 程序,它将在给定边长、x 坐标、y 坐标和旋转角度的情况下生成一个等边三角形。除了旋转外,它按预期工作。 我正在使用旋转矩阵来旋转三角形。这有效,除了它围绕原点旋转而不是原地旋转。 (见下面的例子)。
90 度旋转示例
为了在现场旋转它,我想我需要计算三角形的中心,然后围绕它旋转(不知何故)。我不确定如何做到这一点,或者是否有更简单/更好的方法来做到这一点。我确实看到有一个旋转功能,但据我所知,它适用于球面空间,而不是笛卡尔平面。
代码如下,抱歉,乱码:
function [ side, coord1,coord2 ] = equilateral(side, x,y, rotation)
%EQUILATERAL- given a side length and x,y, coordinates as inputs, the
%function plots an equilateral triangle an angle of rotation can be
%given as an input as well. This will rotate the trianlge around the x
%and y coordinates given.
%rotation argument is not required. If not given, angle is 0
if(exist('rotation','var'))
angle = rotation;
else
angle = 0;
end
%rotation matrix
R = [cos(angle), -sin(angle); sin(angle), cos(angle)];
%Make the axis equal so the triangles look equilateral
axis equal;
%max horizontal x coordinate
x2 = x + side;
%max horiontal y coordinate (equal to original y coordinate)
y2 = y;
%height of the triangle at midpoint (perpendicular height)
h = side*sin(pi/3) + y;
%coordinates of midpoint/top vertice
mid = [x2-(0.5*side), h];
%min coordinates
coord1 = [x,y];
%max coordinates
coord2 = [x2,y2];
if (angle > 0)
coord1 = coord1*R;
coord2 = coord2*R;
mid = mid*R;
end
%plot the base of the triangle
plot(linspace(coord1(1),coord2(1)), linspace(coord1(2),coord2(2)));
hold on
%plot the first side from inital coords to midpoint
plot(linspace(coord1(1),mid(1)), linspace(coord1(2),mid(2)));
%plot second side from mid point to max coords
plot(linspace(mid(1),coord2(1)), linspace(mid(2),coord2(2)));
end
我愿意接受有关改进代码/帮助以清理它以及帮助解决轮换问题的任何建议。感谢您的帮助。
【问题讨论】: