# How to generate a random 3D vector with set magnitude?

9 views (last 30 days)
Adam Nekolny on 23 Jan 2024
Commented: Dyuman Joshi on 23 Jan 2024
Hello, I am currently trying to figure out how to generate a random vector that differs in x,y,z values however thewir total magnitude is always set within a certain precision, so they can vary a bit in magnitude but would want them as close to the one aimed for.
I am currently looking at random generation and thinking about different ways but having trouble thinking how I would implement it in better way than just keep generating the random values until they are close enough.
Any help or guidance is appreciated.
Thank you for yoru time.
Dyuman Joshi on 23 Jan 2024

Hassaan on 23 Jan 2024
targetMagnitude = 10; % Target magnitude of the vector
tolerance = 0.1; % Tolerance for the magnitude
nVectors = 5; % Number of vectors to generate
randomVectors = generateRandomVector(targetMagnitude, tolerance, nVectors);
disp(randomVectors);
-3.9578 8.8378 2.4159 5.5197 -6.9073 4.5746 -0.5939 10.0319 -0.4312 9.8464 1.1230 -1.4840 -4.8208 7.0865 5.0712
function vectors = generateRandomVector(targetMag, tolerance, nVectors)
vectors = zeros(nVectors, 3); % Initialize an array to store the vectors
for i = 1:nVectors
% Generate random angles
theta = 2*pi*rand();
phi = acos(1 - 2*rand());
% Randomly adjust the magnitude within the tolerance
adjustedMag = targetMag + (rand() - 0.5) * 2 * tolerance;
% Convert to Cartesian coordinates
x = adjustedMag * sin(phi) * cos(theta);
y = adjustedMag * sin(phi) * sin(theta);
z = adjustedMag * cos(phi);
% Store the vector
vectors(i, :) = [x, y, z];
end
end
-----------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
It's important to note that the advice and code are based on limited information and meant for educational purposes. Users should verify and adapt the code to their specific needs, ensuring compatibility and adherence to ethical standards.
Professional Interests
• Technical Services and Consulting
• Embedded Systems | Firmware Developement | Simulations
• Electrical and Electronics Engineering
Feel free to contact me.

### More Answers (1)

Bruno Luong on 23 Jan 2024
Edited: Bruno Luong on 23 Jan 2024
MagTarget = 10;
MagRange = 0.5;
n = 1000;
m = MagTarget + MagRange * (rand(1,n)-0.5);
xyz = randn(3,n);
xyz = xyz .* (m ./ sqrt(sum(xyz.^2,1)));
xyz(:,1)
ans = 3×1
1.6927 8.0711 5.7062
norm(ans)
ans = 10.0284
xyz(:,10)
ans = 3×1
2.7756 3.0553 -8.9397
norm(ans)
ans = 9.8466