登录论坛

查看完整版本 : 如何在向量的所有点之间绘制线?


poster
2019-12-10, 16:49
我有一个包含二维空间中某些点的向量。我希望MATLAB使用从每个点到每个其他点绘制的线来绘制这些点。基本上,我想要一个连接所有顶点的图。你能用情节来做吗,如果可以,怎么做?


回答:
一种解决方案是使用函数MESHGRID (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/meshgrid.html)为每个点组合创建一组索引。然后,您可以使用函数LINE (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/line.html) (在给出的数据的每一列中绘制一行)来绘制每条线:

N = 10; %# Number of points x = rand(1,N); %# A set of random x values y = rand(1,N); %# A set of random y values = meshgrid(1:N); %# Create all the combinations of indices index = [I(:) J(:)].'; %'# Reshape the indices line(x(index),y(index),'Color','k'); %# Plot the lines hold on plot(x,y,'r*'); %# Plot the points 编辑:

您可能会注意到,上述解决方案将为[I]每个连接绘制一条线,这意味着它将为连接点绘制零长度的连接线,并为每个连接绘制2条线(即,从A点到B点以及从B点到点一种)。这是另一种解决方案(使用功能HANKEL (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/hankel.html)和FIND (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/find.html) ),不会绘制多余或不必要的线条:

N = 10; %# Number of points x = rand(1,N); %# A set of random x values y = rand(1,N); %# A set of random y values [r,c,v] = find(hankel(2:N)); %# Create unique combinations of indices index = [vc].'; %'# Reshape the indices line(x(index),y(index),'Color','k'); %# Plot the lines hold on plot(x,y,'r*'); %# Plot the points 以上两种解决方案都可以创建视觉上相同的图:

https://i37.photobucket.com/albums/e77/kpeaton/example_network.jpg

关于时间的说明...

出于好奇,我想我应该选择汉克的 (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/hankel.html)解决方案,并将其与Amro的 (https://stackoverflow.com/questions/1702140/how-to-plot-lines-between-all-points-in-vector-in-matlab/1702724#1702724)非常简洁的NCHOOSEK (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/nchoosek.html)解决方案进行比较。对于N = 10 ,没有明显的差异。但是,当我将N增加到更大的值时,我开始看到NCHOOSEK解决方案开始变得非常缓慢:


N = 200

>> tic; [r,c,v] = find(hankel(2:N)); index = [vc].'; toc; %' Elapsed time is 0.009747 seconds. >> tic; pairs = nchoosek(1:N,2).'; toc; %' Elapsed time is 0.063982 seconds.
N = 1000

>> tic; [r,c,v] = find(hankel(2:N)); index = [vc].'; toc; %' Elapsed time is 0.175601 seconds. >> tic; pairs = nchoosek(1:N,2).'; toc; %' Elapsed time is 12.523955 seconds.
在查看了NCHOOSEK的代码之前(在MATLAB命令窗口中type nchoosek ),我感到有些惊讶。不仅变量在循环内增长而不是预先分配 (http://blinkdagger.com/matlab/matlab-speed-up-your-code-by-preallocating-the-size-of-arrays-cells-and-structures/) (如Amro在评论中指出的那样),而且使用的算法也是递归的 ,这意味着要进行许多函数调用。我还在NCHOOSEK的帮助文本末尾注意到了这一行:

此语法仅适用于N小于约15的情况。



更多&回答... (https://stackoverflow.com/questions/1702140)