我有一个包含2-D空间中的一些点的向量.我希望MATLAB用从每个点到每个其他点绘制的线来绘制这些点.基本上,我想要一个连接所有顶点的图形.你可以用情节做到这一点,如果是这样,怎么样?
一种解决方案是使用函数MESHGRID为每个点组合创建一组索引.然后,您可以使用LINE函数绘制每一行(它为每列数据绘制一行):
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
[I,J] = 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
Run Code Online (Sandbox Code Playgroud)
编辑:
您可能会注意到上述解决方案将为每个连接绘制一条线,这意味着它将绘制零长度连接点到自身的线,并为每个连接绘制2条线(即从点A到点B 以及从点B到点一个).这是另一个解决方案(使用函数HANKEL和FIND),它不会绘制冗余或不必要的行:
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 = [v c].';                     %'# Reshape the indices
line(x(index),y(index),'Color','k');  %# Plot the lines
hold on
plot(x,y,'r*');                       %# Plot the points
Run Code Online (Sandbox Code Playgroud)
上述两种解决方案都创建了视觉上相同的图:

关于时间的说明......
出于好奇,我想我会把我的HANKEL解决方案与Amro非常简洁的NCHOOSEK解决方案进行比较.因为N = 10,没有明显的区别.然而,当我增加到N更大的值时,我开始看到NCHOOSEK解决方案开始变得非常缓慢:
N = 200
>> tic; [r,c,v] = find(hankel(2:N)); index = [v c].'; toc; %'
Elapsed time is 0.009747 seconds.
>> tic; pairs = nchoosek(1:N,2).'; toc; %'
Elapsed time is 0.063982 seconds.
Run Code Online (Sandbox Code Playgroud)N = 1000
>> tic; [r,c,v] = find(hankel(2:N)); index = [v c].'; toc; %'
Elapsed time is 0.175601 seconds.
>> tic; pairs = nchoosek(1:N,2).'; toc; %'
Elapsed time is 12.523955 seconds.
Run Code Online (Sandbox Code Playgroud)直到我查看NCHOOSEK的代码(通过键入type nchoosekMATLAB命令窗口),我才感到惊讶.变量不仅在循环内生长而不是预先分配(正如Amro在注释中指出的那样),但所使用的算法也是递归的,这意味着进行了许多函数调用.我还注意到NCHOOSEK帮助文本末尾的这一行:
该语法仅适用于N小于约15的情况.
基于gnovice的例子,一个更简单,更直观的生成所有对的方法是使用nchoosek函数:
%# random points
N = 10;
x = rand(1,N);
y = rand(1,N);
%# all possible combinations of the elements of [1:N] taken 2 at a time
pairs = nchoosek(1:N, 2)';
%'# plot points and lines
plot(x(pairs), y(pairs), '-bs', 'MarkerFaceColor','g', 'MarkerSize',10)
Run Code Online (Sandbox Code Playgroud)
