MATLAB Answers

How can I plot a unit vector in 3-D space?

7 views (last 30 days)
NaviKan
NaviKan on 30 Jul 2020
Commented: NaviKan on 30 Jul 2020
Hello everyone,
I need help in plotting a 3-D unit vector. I was trying to use the "quiver3" command but could n't succeed. Any help or useful suggestions in this regard would be highly appreciated.
The details are:
I have a vector “r” with three components “x”, “y” and “z”. By definition, the unit vector of any vector is that vector divided by its magnitude. What I need to obtain is the corresponding unit vector in 3-D space in terms of arrows spread over x, y, and z coordinates.
Thanks.
clear all
close all
clc
N=101;
x=linspace(-10,10,N);
y=x;
z=y;
for i=1:length(x)
for j=1:length(y)
for k=1:length(z)
r_vec(i,j,k)=x(i)+y(j)+z(k);
r_mag(i,j,k)=sqrt(x(i).^2+y(j).^2+z(k).^2);
r_unit(i,j,k)=r_vec(i,j,k)./r_mag(i,j,k);
end
end
end

  0 Comments

Sign in to comment.

Accepted Answer

KSSV
KSSV on 30 Jul 2020
Edited: KSSV on 30 Jul 2020
You need not to use that complex, time consuming loop to get what you want.
clear all
close all
clc
N=101;
x=linspace(-10,10,N)';
y=x;
z=y;
r_vec = [x y z] ;
r_mag = sqrt(x.^2+y.^2+z.^2) ;
r_unit = r_vec./r_mag ;
quiver3(x,y,z,r_unit(:,1),r_unit(:,2),r_unit(:,3))

  3 Comments

NaviKan
NaviKan on 30 Jul 2020
@ KSSV thanks for your help but still there is a problem in the code. There is a dimension mismatch between r_vec (101X3 ) and r_mag (101X1 ) ,and thus r_unit=r_vec./r_mag does not work. Did you run the code and get the result?
KSSV
KSSV on 30 Jul 2020
Did you run the code?
A vector in 3D should have three components so the size 101*3 is correct. Magnitude is length of the vector, so it will be 101*1. We divide each component with this magnitude. Again r_unit will be a unit vector and it shall have three components so it;s size is 101*3. To check you can find the magnitude of r_unit, you will get all 1's.
u_mag = sqrt(r_unit(:,1).^2+r_unit(:,2).^2+r_unit(:,3).^2) ;
The code is all right. It works.
NaviKan
NaviKan on 30 Jul 2020
Ok, thanks a lot.
It works and agian thanks for your help.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!