一种解决方案是使用函数
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
编辑:
您可能会注意到上述解决方案将为每个连接绘制一条线,这意味着它将绘制零长度连接点到自身的线,并将为每个连接绘制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
上述两种解决方案都创建了视觉上相同的图:
有关时间的说明……
出于好奇,我想我会把我的HANKEL解决方案与Amro’s非常简洁的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.
> 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.
我有点惊讶,直到我查看NCHOOSEK的代码(在MATLAB命令窗口中输入类型nchoosek).变量不仅在循环中生长而不是在preallocated中(正如Amro在注释中指出的那样),但所使用的算法也是递归的,这意味着进行了许多函数调用.我还注意到NCHOOSEK帮助文本末尾的这一行:
This syntax is only practical for situations where N is less than about 15.