我有一个 n 行 4 列的矩阵。列是 x0、y0 和 x1、y1(所以基本上我在 2D 中有 n 对点坐标)。我想在对应的点对之间画一条线(即仅在一行的 x0, y0 和 x1, y1 之间)。
是否可以在没有循环的情况下做到这一点?因为以下工作但很慢。
for i = 1:size(A.data, 1)
plot([A.data(i, 1), A.data(i, 3)], [A.data(i, 2), A.data(i, 4)], 'k-')
end
这适用于我拥有的数据结构:
data = [
0, 0, 1, 0;...
1, 0, 1, 1;...
1, 1, 0, 1;...
0, 1, 0, 0 ...
];
figure(1);
hold off;
%slow way
for i = 1:size(data, 1)
plot([data(i, 1) data(i, 3)], [data(i, 2) data(i, 4)], 'r-');
hold on;
end
%fast way ("vectorized")
plot([data(:, 1)' data(:, 3)'], [data(:, 2)' data(:, 4)'], 'b-');
axis equal
这个特殊的例子画了一个正方形。
关键是 MATLAB在参数中按列绘制线条。也就是说,如果 的参数plot
有n列,则该行将有n -1 段。
在向量中的所有点都必须连接的“连接点”场景中,这是无关紧要的,因为如果需要,MATLAB 会转置以获得列向量。它在我的应用程序中变得很重要,因为我不想连接列表中的每个点 - 只连接点对。
我来到这里寻找相同的答案。我基本上希望每个 x,y 点都有一条水平线,从该点的 xy 值开始,到下一个 xy 对的 x 值结束,没有一条线将该线段连接到下一个 xy 对的线段。我可以通过在旧 y 和新 x 之间添加新点来制作线段,但我不知道如何分解线段。但是你的措辞(矩阵)给了我一个想法。如果您将 xy 对加载到一对 x、y 向量中,然后 - 等待它 - 在 x 和 y 向量中将您的对与 nan 分开会怎样。我用一个很长的正弦波尝试过,它似乎有效。大量不相交的线段,可立即绘制和缩放。:) 看看它是否能解决你的问题。
% LinePairsTest.m
% Test fast plot and zoom of a bunch of lines between disjoint pairs of points
% Solution: put pairs of x1,y1:x2,y2 into one x and one y vector, but with
% pairs separated by x and or y = nan. Nan is wonderful, because it leaves
% your vector intact, but it doesn't plot.
close all; clear all;
n = 10000; % lotsa points
n = floor(n/3); % make an even set of pairs
n = n * 3 - 1; % ends with a pair
x = 1:n; % we'll make a sine wave, interrupted to pairs of points.
% For other use, bring your pairs in to a pair of empty x and y vectors,
% padding between pairs with nan in x and y.
y = sin(x/3);
ix = find(0 == mod(x,3)); % index 3, 6, 9, etc. will get...
x(ix) = nan; % nan.
y(ix) = nan; % nan.
figure;
plot(x,y,'b'); % quick to plot, quick to zoom.
grid on;
line
例如尝试
X=[1:10 ; 2*(1:10)];
Y=fliplr(X);
line(X,Y)