How to generate a random 3D vector with set magnitude?
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.
1 Comment
Dyuman Joshi
on 23 Jan 2024
Accepted Answer
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)
Categories
Find more on Programming 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!