Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I plot a vector-linear equation correctly with matlab?

Tags:

matlab

I have an issue with Matlab. I'm trying to display / plot this linear equation made up by vectors but it's not working - I have tried so many different things.

With "vector-linear equation" I mean something like this (picture):

enter image description here

I have written the following code to do this but it's not plotting anything:

function VectorEq(v1, v2)
    t = linspace(-10*pi, 10*pi);
    x = v1(:,1) + t(:,1)*v2(:,1);
    y = v1(:,2) + t(:,2)*v2(:,2);
    z = v1(:,3) + t(:,3)*v2(:,3);
    plot3(x,y,z);
end

What am I missing here? :/

like image 793
eyesima Avatar asked Feb 26 '26 07:02

eyesima


2 Answers

In the vector form of the equation of a line, t isn't a vector, it's the scalar that multiplies the direction vector. For your problem, you want to find the value of the line equation for each of the values of t

To do this, you can use Matlab's automatic broadcasting of array shapes. For example:

v2 = [1; 2; 3];
t = linspace(0, 1, 5);
v2 * t

This gives:

ans =

        0   0.2500   0.5000   0.7500   1.0000
        0   0.5000   1.0000   1.5000   2.0000
        0   0.7500   1.5000   2.2500   3.0000

Notice that the jth column in the answer corresponds to the jth element of t.

Such a matrix can be added to a column vector, also using broadcasting. For example:

v1 = [11; 12; 13];
v1 + v2 * t

gives

ans =

   11.000   11.250   11.500   11.750   12.000
   12.000   12.500   13.000   13.500   14.000
   13.000   13.750   14.500   15.250   16.000

The rows give you the values of your x, y, and z coordinates.

So to vectorize your problem and quickly obtain the solution:

function VectorEq(v1, v2)
    t = linspace(-10*pi, 10*pi);
    f = v1(:) + v2(:) * t;
    % v1(:) ensures it's a column vector
    plot3(f(1, :), f(2, :), f(3, :));
end

With v1 = [1; 2; 3] and v2 = [0.1; 0.2; 0.3], we get the blue line:

enter image description here

The black dot and vector are the point v1 and the unit vector of v2:

v1 = [1; 2; 3]; v2 = v1 / 10;

uv2 = v2 / norm(v2);

VectorEq(v1, v2);
hold on;
plot3(v1(1), v1(2), v1(3), '.k');
quiver3(v1(1), v1(2), v1(3), uv2(1), uv2(2), uv2(3), 'k');
like image 133
Pranav Hosangadi Avatar answered Feb 28 '26 15:02

Pranav Hosangadi


Here t is going to be a row vector, and doesn't have the three components you seem to assume it has. In this line parametrization t is a scalar, so following method should work:

function VectorEq(v1, v2)
    t = linspace(-10*pi, 10*pi);
    x = v1(:,1) + t*v2(:,1);
    y = v1(:,2) + t*v2(:,2);
    z = v1(:,3) + t*v2(:,3);
    plot3(x,y,z);
end
like image 36
flawr Avatar answered Feb 28 '26 13:02

flawr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!