如何使用MATLAB绘制椭圆和椭球体?
(x^2/a^2)+(y^2/b^2)=1
n=40;
a=0; b=2*pi;
c=0; d=2*pi;
for i=1:n
u=a+(b-a)*(i-1)/(n-1);
for j=1:m
v=a+(d-c)*(j-1)/(m-1);
x(i,j)=sin(u)*cos(v);
y(i,j)=sin(u)*sin(v);
z(i,j)=cos(u);
end
end
mesh(x,y,z);
但我想要这个形状?
发布于 2010-01-28 15:07:59
Wikipedia上的椭圆文章有一个简单的JavaScript代码来绘制椭圆。
它使用参数形式:
x(theta) = a0 + ax*sin(theta) + bx*cos(theta)
y(theta) = b0 + ay*sin(theta) + by*cos(theta)
哪里
(a0,b0) is the center of the ellipse
(ax,ay) vector representing the major axis
(bx,by) vector representing the minor axis
我将代码翻译成MATLAB函数:
calculateEllipse.m
function [X,Y] = calculateEllipse(x, y, a, b, angle, steps)
%# This functions returns points to draw an ellipse
%#
%# @param x X coordinate
%# @param y Y coordinate
%# @param a Semimajor axis
%# @param b Semiminor axis
%# @param angle Angle of the ellipse (in degrees)
%#
narginchk(5, 6);
if nargin<6, steps = 36; end
beta = -angle * (pi / 180);
sinbeta = sin(beta);
cosbeta = cos(beta);
alpha = linspace(0, 360, steps)' .* (pi / 180);
sinalpha = sin(alpha);
cosalpha = cos(alpha);
X = x + (a * cosalpha * cosbeta - b * sinalpha * sinbeta);
Y = y + (a * cosalpha * sinbeta + b * sinalpha * cosbeta);
if nargout==1, X = [X Y]; end
end
下面是一个测试它的例子:
%# ellipse centered at (0,0) with axes length
%# major=20, ,minor=10, rotated 50 degrees
%# (drawn using the default N=36 points)
p = calculateEllipse(0, 0, 20, 10, 50);
plot(p(:,1), p(:,2), '.-'), axis equal
发布于 2010-01-28 14:31:42
我已经从MATLAB Central改编了这个excellent ellipse plotting script,以满足您的需求
function plotEllipse(a,b,C)
% range to plot over
%------------------------------------
N = 50;
theta = 0:1/N:2*pi+1/N;
% Parametric equation of the ellipse
%----------------------------------------
state(1,:) = a*cos(theta);
state(2,:) = b*sin(theta);
% Coordinate transform (since your ellipse is axis aligned)
%----------------------------------------
X = state;
X(1,:) = X(1,:) + C(1);
X(2,:) = X(2,:) + C(2);
% Plot
%----------------------------------------
plot(X(1,:),X(2,:));
hold on;
plot(C(1),C(2),'r*');
axis equal;
grid;
end
注意:更改N以定义椭圆的分辨率
这是一个以(10,10)
为中心的椭圆,带有a = 30
和b = 10
发布于 2010-01-28 10:38:43
创建两个向量,一个是椭球周长的x坐标,另一个是y坐标。使这些向量足够长,以满足您的精度要求。将这两个向量绘制成(x,y)对连接在一起。我会从你的代码中去掉for循环,如果你使用向量符号会更清楚。另外,我会使用代码的SO标记来格式化您的问题,以使您的读者更清楚。
https://stackoverflow.com/questions/2153768
复制相似问题