我有一个包含二维空间中某些点的向量。我希望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
编辑:
您可能会注意到,上述解决方案将为
每个连接绘制一条线,这意味着它将为连接点绘制零长度的连接线,并为每个连接绘制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 = [vc].'; %'# Reshape the indices line(x(index),y(index),'Color','k'); %# Plot the lines hold on plot(x,y,'r*'); %# Plot the points 以上两种解决方案都可以创建视觉上相同的图:
关于时间的说明...
出于好奇,我想我
应该选择汉克的解决方案,并将其与
Amro的非常简洁的
NCHOOSEK解决方案进行比较。对于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 ),我感到有些惊讶。不仅变量在循环内增长而不是
预先分配 (如Amro在评论中指出的那样),而且使用的算法也是
递归的 ,这意味着要进行许多函数调用。我还在NCHOOSEK的帮助文本末尾注意到了这一行:
此语法仅适用于N小于约15的情况。
更多&回答...