MATLAB: Draw lines between two given sets of points

lineplot3

I have two sets of points in 3D. These look for example like:
S1 = {(x1,y1,z1),(x2,y2,z2),…,(xn,yn,zn)}
S2 = {(x1',y1',z1'),(x2',y2',z2'),…,(xn',yn',zn')}
So both sets have the same number of points and I would like to connect them with lines like:
(x1,y1,z1) —- (x1',y1',z1')
(x2,y2,z2) —- (x2',y2',z2')
.
.
.
(xn,yn,zn) —- (xn',yn',zn')
What would be the best way to achieve that at once? I could do that with a for-loop which will plot a line between each two points, but I am asking, if there's a way I could organise the data so that all lines can be plotted at the same time?…
Thanks very much for your help in advance!
Best Regards,
Ahmed Hossam

Best Answer

% Create some test data:
S1 = cell(1, 5);
for k = 1:5, S1{k} = rand(1, 3); end
S2 = cell(1, 5);
for k = 1:5, S2{k} = rand(1, 3); end
M1 = cat(1, S1{:}).';
M2 = cat(1, S2{:}).';
plot3([M1(1, :); M2(1, :)], [M1(2, :); M2(2, :)], [M1(3, :); M2(3, :)]);
Or equivalent:
M1 = cat(3, S1{:});
M2 = cat(3, S2{:});
M = permute(cat(1, M1, M2), [1, 3, 2]);
plot3(M(:, :, 1), M(:, :, 2), M(:, :, 3))