How to plot a circle on a spherical surface?

35 次查看(过去 30 天)
I have written a code which plots a circle(with center (x,y) and radius r) on the surface of a sphere. But, it does not work properly in the boundary, that is near y=0. The code:
close all; clear all; clc
N=100;
[X,Y,Z]=sphere(N);
C=zeros(N+1,N+1);
x=75;
y=1;
r=15;
for i=1:N+1
for j=1:N+1
d=sqrt(((i-x)^2)+((j-y)^2));
if (d<=r)
C(i,j)=1;
end
end
end
figure
surf(X,Y,Z,C)
axis equal
% shading interp
% light
The code works properly for values of y>r like y=15,16,17... Can anybody please help to make it work for values of y less than r?

回答(1 个)

KALASH
KALASH 2024-8-25,18:57
编辑:Walter Roberson 2024-8-25,19:06
I understand that you want to plot a circle on the surface of the sphere. The issue you're encountering is related to how the circle is defined on the surface of the sphere. When y is close to zero, the circle might be partially or entirely outside the bounds of the sphere's surface parameterization due to the way you're calculating the distance d in a Cartesian coordinate system rather than on the sphere's surface.
Have a look at the below code for a possible solution:
close all; clear all; clc
N = 100;
[X, Y, Z] = sphere(N);
% Parameters for the circle
x = 75; % Longitude in degrees
y = 1; % Latitude in degrees
r = 15; % Radius in degrees
% Convert degrees to radians for computation
x_rad = deg2rad(x);
y_rad = deg2rad(y);
r_rad = deg2rad(r);
% Calculate the circle's center in Cartesian coordinates
center_x = cos(y_rad) * cos(x_rad);
center_y = cos(y_rad) * sin(x_rad);
center_z = sin(y_rad);
% Create a circle in spherical coordinates
theta = linspace(0, 2*pi, 100);
circle_x = cos(r_rad) * cos(theta);
circle_y = cos(r_rad) * sin(theta);
circle_z = sin(r_rad) * ones(size(theta));
% Rotate circle to the correct position on the sphere
% Rotation matrix to align the circle with the sphere's surface
R = [cos(x_rad), -sin(x_rad), 0; sin(x_rad), cos(x_rad), 0; 0, 0, 1] * ...
[cos(y_rad), 0, sin(y_rad); 0, 1, 0; -sin(y_rad), 0, cos(y_rad)];
circle_points = R * [circle_x; circle_y; circle_z];
% Plot the sphere
figure
surf(X, Y, Z, 'FaceAlpha', 0.5, 'EdgeColor', 'none');
hold on
% Plot the circle on the sphere
plot3(circle_points(1, :), circle_points(2, :), circle_points(3, :), 'r-', 'LineWidth', 2);
% Set the view and other plot properties
axis equal
xlabel('X')
ylabel('Y')
zlabel('Z')
title('Circle on Sphere')
grid on
hold off
Here is the output of the above code in my MATLAB R2023b:
To get more information on the plot functions of MATLAB, have a look at the following documentation:
Hope this resolves the problem!

类别

Help CenterFile Exchange 中查找有关 Surface and Mesh Plots 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by