Matlab: I have two points in a 3D plot and i want

2020-03-08 06:20发布

问题:

I have a 3D plot and two points coordinates A(0,0,0) and B(13,-11,19). I just want to plot a visible line connecting this two points ... I tried plot3(0,0,0, 13,-11,19) and other stuff but everything i tried failed miserably.

回答1:

Here's how:

% Your two points
P1 = [0,0,0];
P2 = [13,-11,19];

% Their vertial concatenation is what you want
pts = [P1; P2];

% Because that's what line() wants to see    
line(pts(:,1), pts(:,2), pts(:,3))

% Alternatively, you could use plot3:
plot3(pts(:,1), pts(:,2), pts(:,3))

Admittedly, this might seem a bit counter-intuitive at first, but in the long run it'll make sense.

If you read doc plot or doc line, you'll see that each expects sets of x, y and z data, respectively. That is, using

plot3(X,Y,Z)

with X, Y and Z some matrices, plot3 will draw a line from the first triplet (X(1) Y(1) Z(1)) to the second triplet (X(2) Y(2) Z(2)) and so on -- same for line.