How to generate a random 3D vector with set magnitude?
14 views (last 30 days)
Show older comments
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.
Accepted Answer
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);
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.
0 Comments
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)
norm(ans)
xyz(:,10)
norm(ans)
0 Comments
See Also
Categories
Find more on Waveform Generation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!