MATLAB galaxy system/ planetary orbit - matlab

"Particles are centered at [0 0]. There are (free) particles moving around the center. Color interpolation is adopted to color the colors of the free particles.
t begins at 0. The particle position is randomly generated within a region in a uniform manner. A point p is inside the region iff (if only if), 50>=||p|| >= 10. Here, ||p|| is the distance between p and the origin [0 0]. Initialize the velocity of each particle so that it is orthogonal to the vector (p-[0 0]).
Velocity normalization: Make the velocity of the particle p orthogonal to the vector p – [0 0].
Assume p = [x y]. Then the velocity is
A) s * [y -x] /||p|| or
B) s * [ -y x]/||p||
Set s to 20. If you adopt the same rule (A or B) to set the velocities of all the particles, all the particles rotate in the same direction.
Color interpolation: The color of a particle depends on the distance, d, of the particle to the origin [0 0].
"
This is an old midterm question from a class. Here is my answer:
t = 0;
p = zeros(1,2); v = [0,0];
dt = 0.05;
M = 10000; m= 1;
tmax = 100;
figure, hold on
d = 0.025;
cp0 = [ 0 0 1]; %blue
cp1 = [ 1 0 0]; % red
n=50; s=20;
clf;
for i = 1:n
for j = 1:n
p([i,j]) = [10 + (50-10) .* rand(1,1),(10 + (50-10) .* rand(1,1))];
end
end
while t < tmax
for k= 1:n
for l = 1:n
F = -(p([k,l])./norm(p)).*(m*M./(1+p([k,l]).*p([k,l])));
a = F/m;
v = v + a.*dt;
v = s.*[-k,l]./norm(p);
d = norm([0,0] - p([k,l]))
p([k,l]) = p([k,l]) + v.*dt;
vD = min(1, d/50);
particle_color = cp0 + vD*(cp1-cp0); %color interpolation
end
clf;
plot(p,'o','MarkerEdgeColor',particle_color);
axis([-80 80 -80 80]); hold on
pause(0.05);
t = t + dt;
end
end
In my code, why are the particles not moving in circular motion?

Related

Plot two-dimensional array as elliptical orbit

I am attempting to plot an elliptical orbit based on a 2-D position array, beginning at p= [5 0]. The plot charts positions from a timeframe t, here between 0 and 100. The calculation uses the formula F = -(p/||p||)(m*M/(p^2) to approximate acceleration and velocity. The result should look like the following:
This is my current code. It plots a completely different shape. Is the problem in my way of interpreting the force equation?
Any other help and comments are much appreciated.
t = 0; p = [50 0]; v = [0 8]; %Initial conditions
dt = 0.05;
M = 10000; m= 1;
tmax = 100;
figure, hold on
d = 0.001
clf;
while t < tmax
F = -(p./norm(p)).*(m*M./(p*p'));
a = F./m - d*v;
v = v + a*dt;
p = p + v*dt;
t = t + dt;
plot(p(1),t,'o','MarkerSize',0.5);
hold on;
plot(p(2),t,'o','MarkerSize',0.5);
end
You want p(1) in the x axis and p(2) in the y axis, with t as a parameter. So you need to replace the two plot lines by plot(p(1),p(2),'o','MarkerSize',0.5); (keeping hold on):
t = 0; p = [50 0]; v = [0 8]; %Initial conditions
dt = 0.05;
M = 10000; m= 1;
tmax = 100;
figure, hold on
d = 0.001
clf;
while t < tmax
F = -(p./norm(p)).*(m*M./(p*p'));
a = F./m - d*v;
v = v + a*dt;
p = p + v*dt;
t = t + dt;
hold on
plot(p(1),p(2),'o','MarkerSize',0.5); %%% modified line
end

MATLAB plotting trajectory

I would like to plot the angular velocity of point B by using MATLAB. However, there is some mistake in my code for angular velocity that I couldn't fix.
The length of the input link OA of the mechanism is r = 50 mm, length of AB is l = 150 mm. Fixed coordinates of point C are xC = d = 80 mm and yC = 0 mm.
Angular velocity of OA is ω = 15 rad/s.
%Full trajectory of B
%Linkage dimensions
clear
r = 50;
l = 150;
xC = 80;
yC = 0;
n = 361; % Number of position calculations
fii = linspace(0,2*pi,n);
omega = 15;
[xA,yA] = pol2cart(fii,r);
d = xA + xC;
alpha = atan(yA./(xC-xA));
lx = l*cos(alpha);
ly = l*sin(alpha);
xB = xA + lx;
yB = yA + ly;
plot(xB,yB) %Plots the trajectory
title('Full trajectory of AB')
% Angular velocity of AB
for ind = 1:n
omegaAB(ind) = (-(r^2-d*r*cos(fii))/(r^2 + d^2 - 2*d*r*cos(fii)))*omega;
end
figure(2)
plot(fii,omegaAB, 'linewidth', 2, 'color', 'red')
title('Angular velocity of AB')
ylabel('\omega_{AB} [1/s]')
xlabel('\phi [rad]')
I think there is just one mistake in your code when you compute alpha:
alpha = atan(yA./(xC-xA));
This gives the following trajectory:
Your code is partially vectorized but you're still looping over ind which is why you are getting matrix dimensions errors. You can either remove the loop and make it completely vectorized or you can make sure that all of your vectors with length n are indexed properly:
for ind = 1:n
omegaAB(ind) = (-(r^2-d*r*cos(fii(ind)))/(r^2 + d(ind)^2 - 2*d*r*cos(fii(ind))))*omega;
end

Create random unit vector inside a defined conical region

I'm looking for a simple way for creating a random unit vector constrained by a conical region. The origin is always the [0,0,0].
My solution up to now:
function v = GetRandomVectorInsideCone(coneDir,coneAngleDegree)
coneDir = normc(coneDir);
ang = coneAngleDegree + 1;
while ang > coneAngleDegree
v = [randn(1); randn(1); randn(1)];
v = v + coneDir;
v = normc(v);
ang = atan2(norm(cross(v,coneDir)), dot(v,coneDir))*180/pi;
end
My code loops until the random generated unit vector is inside the defined cone. Is there a better way to do that?
Resultant image from test code bellow
Resultant frequency distribution using Ahmed Fasih code (in comments).
I wonder how to get a rectangular or normal distribution.
c = [1;1;1]; angs = arrayfun(#(i) subspace(c, GetRandomVectorInsideCone(c, 30)), 1:1e5) * 180/pi; figure(); hist(angs, 50);
Testing code:
clearvars; clc; close all;
coneDir = [randn(1); randn(1); randn(1)];
coneDir = [0 0 1]';
coneDir = normc(coneDir);
coneAngle = 45;
N = 1000;
vAngles = zeros(N,1);
vs = zeros(3,N);
for i=1:N
vs(:,i) = GetRandomVectorInsideCone(coneDir,coneAngle);
vAngles(i) = subspace(vs(:,i),coneDir)*180/pi;
end
maxAngle = max(vAngles);
minAngle = min(vAngles);
meanAngle = mean(vAngles);
AngleStd = std(vAngles);
fprintf('v angle\n');
fprintf('Direction: [%.3f %.3f %.3f]^T. Angle: %.2fº\n',coneDir,coneAngle);
fprintf('Min: %.2fº. Max: %.2fº\n',minAngle,maxAngle);
fprintf('Mean: %.2fº\n',meanAngle);
fprintf('Standard Dev: %.2fº\n',AngleStd);
%% Plot
figure;
grid on;
rotate3d on;
axis equal;
axis vis3d;
axis tight;
hold on;
xlabel('X'); ylabel('Y'); zlabel('Z');
% Plot all vectors
p1 = [0 0 0]';
for i=1:N
p2 = vs(:,i);
plot3ex(p1,p2);
end
% Trying to plot the limiting cone, but no success here :(
% k = [0 1];
% [X,Y,Z] = cylinder([0 1 0]');
% testsubject = surf(X,Y,Z);
% set(testsubject,'FaceAlpha',0.5)
% N = 50;
% r = linspace(0, 1, N);
% [X,Y,Z] = cylinder(r, N);
%
% h = surf(X, Y, Z);
%
% rotate(h, [1 1 0], 90);
plot3ex.m:
function p = plot3ex(varargin)
% Plots a line from each p1 to each p2.
% Inputs:
% p1 3xN
% p2 3xN
% args plot3 configuration string
% NOTE: p1 and p2 number of points can range from 1 to N
% but if the number of points are different, one must be 1!
% PVB 2016
p1 = varargin{1};
p2 = varargin{2};
extraArgs = varargin(3:end);
N1 = size(p1,2);
N2 = size(p2,2);
N = N1;
if N1 == 1 && N2 > 1
N = N2;
elseif N1 > 1 && N2 == 1
N = N1
elseif N1 ~= N2
error('if size(p1,2) ~= size(p1,2): size(p1,2) and/or size(p1,2) must be 1 !');
end
for i=1:N
i1 = i;
i2 = i;
if i > N1
i1 = N1;
end
if i > N2
i2 = N2;
end
x = [p1(1,i1) p2(1,i2)];
y = [p1(2,i1) p2(2,i2)];
z = [p1(3,i1) p2(3,i2)];
p = plot3(x,y,z,extraArgs{:});
end
Here’s the solution. It’s based on the wonderful answer at https://math.stackexchange.com/a/205589/81266. I found this answer by googling “random points on spherical cap”, after I learned on Mathworld that a spherical cap is this cut of a 3-sphere with a plane.
Here’s the function:
function r = randSphericalCap(coneAngleDegree, coneDir, N, RNG)
if ~exist('coneDir', 'var') || isempty(coneDir)
coneDir = [0;0;1];
end
if ~exist('N', 'var') || isempty(N)
N = 1;
end
if ~exist('RNG', 'var') || isempty(RNG)
RNG = RandStream.getGlobalStream();
end
coneAngle = coneAngleDegree * pi/180;
% Generate points on the spherical cap around the north pole [1].
% [1] See https://math.stackexchange.com/a/205589/81266
z = RNG.rand(1, N) * (1 - cos(coneAngle)) + cos(coneAngle);
phi = RNG.rand(1, N) * 2 * pi;
x = sqrt(1-z.^2).*cos(phi);
y = sqrt(1-z.^2).*sin(phi);
% If the spherical cap is centered around the north pole, we're done.
if all(coneDir(:) == [0;0;1])
r = [x; y; z];
return;
end
% Find the rotation axis `u` and rotation angle `rot` [1]
u = normc(cross([0;0;1], normc(coneDir)));
rot = acos(dot(normc(coneDir), [0;0;1]));
% Convert rotation axis and angle to 3x3 rotation matrix [2]
% [2] See https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
crossMatrix = #(x,y,z) [0 -z y; z 0 -x; -y x 0];
R = cos(rot) * eye(3) + sin(rot) * crossMatrix(u(1), u(2), u(3)) + (1-cos(rot))*(u * u');
% Rotate [x; y; z] from north pole to `coneDir`.
r = R * [x; y; z];
end
function y = normc(x)
y = bsxfun(#rdivide, x, sqrt(sum(x.^2)));
end
This code just implements joriki’s answer on math.stackexchange, filling in all the details that joriki omitted.
Here’s a script that shows how to use it.
clearvars
coneDir = [1;1;1];
coneAngleDegree = 30;
N = 1e4;
sol = randSphericalCap(coneAngleDegree, coneDir, N);
figure;plot3(sol(1,:), sol(2,:), sol(3,:), 'b.', 0,0,0,'rx');
grid
xlabel('x'); ylabel('y'); zlabel('z')
legend('random points','origin','location','best')
title('Final random points on spherical cap')
Here is a 3D plot of 10'000 points from the 30° spherical cap centered around the [1; 1; 1] vector:
Here’s 120° spherical cap:
Now, if you look at the histogram of the angles between these random points at the coneDir = [1;1;1], you will see that the distribution is skewed. Here’s the distribution:
Code to generate this:
normc = #(x) bsxfun(#rdivide, x, sqrt(sum(x.^2)));
mysubspace = #(a,b) real(acos(sum(bsxfun(#times, normc(a), normc(b)))));
angs = arrayfun(#(i) mysubspace(coneDir, sol(:,i)), 1:N) * 180/pi;
nBins = 16;
[n, edges] = histcounts(angs, nBins);
centers = diff(edges(1:2))*[0:(length(n)-1)] + mean(edges(1:2));
figure('color','white');
bar(centers, n);
xlabel('Angle (degrees)')
ylabel('Frequency')
title(sprintf('Histogram of angles between coneDir and random points: %d deg', coneAngleDegree))
Well, this makes sense! If you generate points from the 120° spherical cap around coneDir, of course the 1° cap is going to have very few of those samples, whereas the strip between the 10° and 11° caps will have far more points. So what we want to do is normalize the number of points at a given angle by the surface area of the spherical cap at that angle.
Here’s a function that gives us the surface area of the spherical cap with radius R and angle in radians theta (equation 16 on Mathworld’s spherical cap article):
rThetaToH = #(R, theta) R * (1 - cos(theta));
rThetaToS = #(R, theta) 2 * pi * R * rThetaToH(R, theta);
Then, we can normalize the histogram count for each bin (n above) by the difference in surface area of the spherical caps at the bin’s edges:
figure('color','white');
bar(centers, n ./ diff(rThetaToS(1, edges * pi/180)))
The figure:
This tells us “the number of random vectors divided by the surface area of the spherical segment between histogram bin edges”. This is uniform!
(N.B. If you do this normalized histogram for the vectors generated by your original code, using rejection sampling, the same holds: the normalized histogram is uniform. It’s just that rejection sampling is expensive compared to this.)
(N.B. 2: note that the naive way of picking random points on a sphere—by first generating azimuth/elevation angles and then converting these spherical coordinates to Cartesian coordinates—is no good because it bunches points near the poles: Mathworld, example, example 2. One way to pick points on the entire sphere is sampling from the 3D normal distribution: that way you won’t get bunching near poles. So I believe that your original technique is perfectly appropriate, giving you nice, evenly-distributed points on the sphere without any bunching. This algorithm described above also does the “right thing” and should avoid bunching. Carefully evaluate any proposed algorithms to ensure that the bunching-near-poles problem is avoided.)
it is better to use spherical coordinates and convert it to cartesian coordinates:
coneDirtheta = rand(1) * 2 * pi;
coneDirphi = rand(1) * pi;
coneAngle = 45;
N = 1000;
%perfom transformation preventing concentration of points around the pole
rpolar = acos(cos(coneAngle/2*pi/180) + (1-cos(coneAngle/2*pi/180)) * rand(N, 1));
thetapolar = rand(N,1) * 2 * pi;
x0 = rpolar .* cos(thetapolar);
y0 = rpolar .* sin(thetapolar);
theta = coneDirtheta + x0;
phi = coneDirphi + y0;
r = rand(N, 1);
x = r .* cos(theta) .* sin(phi);
y = r .* sin(theta) .* sin(phi);
z = r .* cos(phi);
scatter3(x,y,z)
if all points should be of length 1 set r = ones(N,1);
Edit:
since intersection of cone with sphere forms a circle first we create random points inside a circle with raduis of (45 / 2) in polar coordinates and as #Ahmed Fasih commented to prevent concentration of points near the pole we should first transform this random points, then convert polar to cartesian 2D coordinates to form x0 and y0
we can use x0 and y0 as phi & theta angle of spherical coordinates and add coneDirtheta & coneDirphi as offsets to these coordinates.
then convert spherical to cartesian 3D coordinates

Graphically represent density of iterations

Kind all,
I am working in MATLAB and I'm using Monte Carlo techniques to fit a model. Basically, if we assume that my model is a simple function such as
y=m*x^2+c
And that both my parameters m and c vary between 0.5 and 10, I may randomly draw from such a parameter space and obtain each time a new y. If I plot all my realizations of y I obtain something similar to the following figure:
Is there a way to represent the DENSITY of the realizations? I mean, is there a way (instead of plotting all the realizations) to obtain some kind of contour plot that lies between the minimum of my iterations and the maximum for which its color represents the amount of realizations that fall within a certain interval?
Thanks all!
This isn't very pretty, but you could vary the parameters and play with the scatter/plotting, to make it a bit more visually appealing.
Also I assumed a gaussian distribution instead of your random one (totally random coloring will give you a uniform density). Also this code could be optimized for speed.
n = 1000;
l = 100;
x = linspace(1, 10, l);
y = repmat(x.^2, n, 1);
c = repmat(normrnd(1, 1, n, 1), 1, l);
m = repmat(normrnd(1, 1, n, 1), 1, l);
y = y.*m + c;
p = plot(y', '.');
figure; hold on;
for i = 1:l
[N,edges,bin] = histcounts(y(:, i));
density = N./sum(N);
c = zeros(n, 3);
for j = 1:n
c(j, :) = [1-density(bin(j))/max(density), 1-density(bin(j))/max(density), 1-density(bin(j))/max(density)];
end
scatter(ones(n, 1)*x(i),y(:, i),[],c,'filled');
end
Gives
This creates a histogram of y values for every position in x, then calculates the probability density for each y-value and colors in the points. Here, the y-values for every position x are normalized individually, to color the points according to the overall density of the plot you need to renormalize.
You can calculate y for discrete points of x, while setting random values for c and m. Then using hist function you can find a "not-normalized density" of function values for a given x. You can then normalize it to get a real density of the values, so that the overall area under the distribution curve sums up to 1.
In order to visualize it, you construct a mesh grid [X, Y] along the values of x and y and put the density values as Z. Now you can either plot the surf or its contour plot.
Here is the code:
clear;
n = 1000000; %number of simulation steps
%parameter ranges
m_min = 0.5; m_max = 10;
c_min = 0.5; c_max = 10;
%x points
x_min = 1; x_max = 4; x_count = 100;
x = linspace(x_min, x_max, x_count);
x2 = x.^2;
y_min = 0; y_max = m_max*x_max*x_max + c_max; y_step = 1;
m = rand(n, 1)*(m_max - m_min) + m_min;
c = rand(n, 1)*(c_max - c_min) + c_min;
c = repmat(c, 1, x_count);
y = m*x2 + c;
x_step = (x_max- x_min)/(x_count-1);
[X, Y] = meshgrid(x_min:x_step:x_max, y_min-y_step:y_step:y_max+y_step);
Z = zeros(size(X));
bins = y_min:y_step:y_max;
for i=1:x_count
[n_hist,y_hist] = hist(y(:, i), bins);
%add zeros on both sides to close the profile
n_hist = [0 n_hist 0];
y_hist = [y_min-y_step y_hist y_max+y_step];
%normalization
S = trapz(y_hist,n_hist); %area under the bow
n_hist = n_hist/S; %scaling of the bow
Z(:, i) = n_hist';
end
surf(X, Y, Z, 'EdgeColor','none');
colormap jet;
xlim([x_min x_max]);
ylim([y_min y_max]);
xlabel('X');
ylabel('Y');
figure
contour(X,Y,Z, 20);
colormap jet;
colorbar;
grid on;
title('Density as function of X');
xlabel('X');
ylabel('Y');
Another interesting view is a plot of each section depending on the x value:
Here is the code for this plot:
clear;
n = 1000000; %number of simulation steps
%parameter ranges
m_min = 0.5; m_max = 10;
c_min = 0.5; c_max = 10;
%x points
x_min = 1; x_max = 4; x_count = 12;
x = linspace(x_min, x_max, x_count);
x2 = x.^2;
m = rand(n, 1)*(m_max - m_min) + m_min;
c = rand(n, 1)*(c_max - c_min) + c_min;
c = repmat(c, 1, x_count);
y = m*x2 + c;
%colors for the plot
colors = ...
[ 0 0 1; 0 1 0; 1 0 0; 0 1 1; 1 0 1; 0 0.75 0.75; 0 0.5 0; 0.75 0.75 0; ...
1 0.50 0.25; 0.75 0 0.75; 0.7 0.7 0.7; 0.8 0.7 0.6; 0.6 0.5 0.4; 1 1 0; 0 0 0 ];
%container for legend entries
legend_list = cell(1, x_count);
for i=1:x_count
bin_number = 30; %number of histogramm bins
[n_hist,y_hist] = hist(y(:, i), bin_number);
n_hist(1) = 0; n_hist(end) = 0; %set first and last values to zero
%normalization
S = trapz(y_hist,n_hist); %area under the bow
n_hist = n_hist/S; %scaling of the bow
plot(y_hist,n_hist, 'Color', colors(i, :), 'LineWidth', 2);
hold on;
legend_list{i} = sprintf('Plot of x = %2.2f', x(i));
end
xlabel('y');
ylabel('pdf(y)');
legend(legend_list);
title('Density depending on x');
grid on;
hold off;

How can I describe lines moving radially outwards from a center point?

I have a point in 3d space (x,y,z). I want to move radially outward from that point discretely (say for r=1 and r=2). In the x,y plane I can simply move outward by stepping ((x+r cos(theta)), (y+r sin(theta)), z) with r = 1 or 2 and theta varying every, say 10 degrees.
However, I am unsure how to describe this movement if I want to have lines moving outward on a tilted plane and step my lines within this plane.
I thought it would be just using spherical coordinates. But if I'm drawing lines from a center point using (x=rho sin phi cos theta, y=..., z=...) won't that form a cone rather than a circle tilted on a plane?
P.S. Will be implementing this in MATLAB
You could first make the coordinates going outwards from P0 and then rotate the coordinates using a rotation matrix.
So you take points P for all R's and thetas, as MBo pointed out:
P = [ P0x + R * cos(theta); P0y + R * sin(theta); 0 ]
Then you make a rotation matrix that rotates the XY plane with the angles you want
If you multiply that with your coordinates you get the rotated coordinates. For example a 90 degree rotation about the Z axis for the point [1,0,0]:
However you probably want to rotate about the point P0 and not about the origin, then you have to make an affine matrix with the following translation:
tx = x- r00 * x - r01 * y - r02 * z
ty = y- r10 * x - r11 * y - r12 * z
tz = z- r20 * x - r21 * y - r22 * z
And then make an affine transformation matrix with T and R (designated as M in the figure, sorry):
In this figure Q are the old coordinates and Q' the new coordinates.
I had a similar problem and used this answer and adjusted it to your problem:
%input point and rotated plane
p0 = [10;10;10;1]; % the last entry is your homogeneous dimension
r0 = [45,45,45]; r0 = r0*pi/180;
%rotation to plane
Rx=[1 0 0 0;
0 cos(r0(1)) sin(r0(1)) 0;
0 -sin(r0(1)) cos(r0(1)) 0;
0 0 0 1];
Ry=[cos(r0(2)) 0 -sin(r0(2)) 0;
0 1 0 0;
sin(r0(2)) 0 cos(r0(2)) 0;
0 0 0 1];
Rz=[cos(r0(3)) sin(r0(3)) 0 0;
-sin(r0(3)) cos(r0(3)) 0 0;
0 0 1 0;
0 0 0 1];
R = Rz*Ry*Rx; A = R;
T = ( eye(3)-R(1:3,1:3) ) * p0(1:3); %calculate translation to rotate about the point P0
A(1:3,4) = T; % to rotate about the origin just leave out this line
%make coordinates for the points going outward from p0
nangles = 36; anglestep = 2*pi/nangles;
nradii = 2; radiistep = 1;
thetas = anglestep:anglestep:2*pi;
rs = radiistep:radiistep:nradii*radiistep;
npoints = nradii*nangles;
coordinates = zeros(4,npoints); curpoint = 0;
for itheta = 1:nangles; for iradius = 1:nradii;
curpoint = curpoint+1;
coordinates(:, curpoint) = p0+rs(iradius)*[cos(thetas(itheta));sin(thetas(itheta));0;0];
end; end
coordinates_tilted = A*coordinates; %rotate the coordinates to the new plane
Which results in this figure:
figure;
scatter3(coordinates_tilted(1,:),coordinates_tilted(2,:),coordinates_tilted(3,:), 'MarkerEdgeColor', 'green')
hold on
scatter3(coordinates(1,:),coordinates(2,:),coordinates(3,:), 'MarkerEdgeColor', 'red')
legend('tilted', 'original')
Or plot them as lines:
%or as lines
coorarray = reshape(coordinates, [4 nradii nangles]);
Xline = squeeze(coorarray(1,:,:));
Yline = squeeze(coorarray(2,:,:));
Zline = squeeze(coorarray(3,:,:));
coorarray_tilted = reshape(coordinates_tilted, [4 nradii nangles]);
Xline_tilted = squeeze(coorarray_tilted(1,:,:));
Yline_tilted = squeeze(coorarray_tilted(2,:,:));
Zline_tilted = squeeze(coorarray_tilted(3,:,:));
figure;
plot3(Xline,Yline,Zline, 'r');
hold on
plot3(Xline_tilted,Yline_tilted,Zline_tilted, 'g');
legend( 'original', 'tilted')
Does this answer your question? These are now points at all multiples of 36 degree angles at a distance of one and two from point P0 in the plane that is tilted 45 degrees on all axes around the point P0. If you need individual 'pixels' to designate your line (so integer coordinates) you can round the coordinates and that would be sort of a nearest neighbour approach:
coordinates_tilted_nearest = round(coordinates_tilted);
How is your tilted plane defined?
Define it with base point P0 and two perpendicular unit vectors U and V. It is not hard to get this representation from any other. For example, if normal vector of your plane have angles ax, ay, az with axes OX, OY, OZ respectively, it's normalized form is N = (nx, ny, nz) = (Cos(ax), Cos(ay), Cos(az)). You can choose arbitrary vector U (lying in the plane) as described here, and find V vector as vector product V = U x N
Then needed points are:
P = P0 + U * R * Cos(Theta) + V * R * Sin(Theta)