![]() |
如何在向量的所有点之间绘制线?
我有一个包含二维空间中某些点的向量。我希望MATLAB使用从每个点到每个其他点绘制的线来绘制这些点。基本上,我想要一个连接所有顶点的图。你能用情节来做吗,如果可以,怎么做?
回答: 一种解决方案是使用函数[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/meshgrid.html"]MESHGRID[/URL]为每个点组合创建一组索引。然后,您可以使用函数[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/line.html"]LINE[/URL] (在给出的数据的每一列中绘制一行)来绘制每条线: 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 [B]编辑:[/B] 您可能会注意到,上述解决方案将为[I]每个[/I]连接绘制一条线,这意味着它将为连接点绘制零长度的连接线,并为每个连接绘制2条线(即,从A点到B点[I]以及[/I]从B点到点一种)。这是另一种解决方案(使用功能[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/hankel.html"]HANKEL[/URL]和[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/find.html"]FIND[/URL] ),不会绘制多余或不必要的线条: 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 以上两种解决方案都可以创建视觉上相同的图: [IMG]https://i37.photobucket.com/albums/e77/kpeaton/example_network.jpg[/IMG] [B]关于时间的说明...[/B] 出于好奇,我想我[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/hankel.html"]应该选择汉克的[/URL]解决方案,并将其与[URL="https://stackoverflow.com/questions/1702140/how-to-plot-lines-between-all-points-in-vector-in-matlab/1702724#1702724"]Amro的[/URL]非常简洁的[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/nchoosek.html"]NCHOOSEK[/URL]解决方案进行比较。对于N = 10 ,没有明显的差异。但是,当我将N增加到更大的值时,我开始看到NCHOOSEK解决方案开始变得[I]非常[/I]缓慢: [LIST][*] [B]N = 200[/B] >> 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.[*] [B]N = 1000[/B] >> 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.[/LIST]在查看了NCHOOSEK的代码之前(在MATLAB命令窗口中type nchoosek ),我感到有些惊讶。不仅变量在循环内增长而不是[URL="http://blinkdagger.com/matlab/matlab-speed-up-your-code-by-preallocating-the-size-of-arrays-cells-and-structures/"]预先分配[/URL] (如Amro在评论中指出的那样),而且使用的算法也是[I]递归的[/I] ,这意味着要进行许多函数调用。我还在NCHOOSEK的帮助文本末尾注意到了这一行: [INDENT]此语法仅适用于N小于约15的情况。 [/INDENT] [url=https://stackoverflow.com/questions/1702140]更多&回答...[/url] |
所有时间均为北京时间。现在的时间是 10:31。 |
Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.