Looped vector calculation and storage of answer

2 次查看(过去 30 天)
Hello, I have two horizontal vectors which contain points for plotting a circle; vector "x" for x-coordinates and vector "y" for y-coordinates. I am trying to write a piece of code which will determine the largest chord within that circle. The approach I am taking is to use the distance formula (sqrt((x2-x1)^2)+((y2-y1)^2)) and calculate the distance between the first point and the rest - store all the distances. Then the distance between the second point and the rest - store all distance to same place. And continue this till the last point. In the end I shall have a vector (or matrix) which contains all these distances, I can then run a "max" command to find the maximum distance. I am just not sure how to implement this into MatLab, in a neat looped script. All and any help will be greatly appreciated.

采纳的回答

Matt J
Matt J 2013-7-11
编辑:Matt J 2013-7-11
You can use my interdists() function below. Since you say it is a circle, I don't see why you would want to compare all pairs of points. The only way this can give you a good approximation of the diameter is if the circle is well-sampled, and in that case, the distance to one particular point ,e.g.,
data=[x;y];
distances = interdists(data(:,1),data);
ought to be enough.
function Graph=interdists(A,B)
%Finds the matrix of distances between point coordinates
%
% (1) Graph=interdists(A,B)
%
% in:
%
% A: matrix whose columns are coordinates of points, for example
% [[x1;y1;z1], [x2;y2;z2] ,..., [xM;yM;zM]]
% but the columns may be points in a space of any dimension, not just 3D.
%
% B: A second matrix whose columns are coordinates of points in the same
% Euclidean space. Default B=A.
%
%
% out:
%
% Graph: The MxN matrix of separation distances in l2 norm between the coordinates.
% Namely, Graph(i,j) will be the distance between A(:,i) and B(:,j).
%
%
% (2) interdists(A,'noself') is the same as interdists(A), except the output
% diagonals will be NaN instead of zero. Hence, for example, operations
% like min(interdists(A,'noself')) will ignore self-distances.
%
% See also getgraph
noself=false;
if nargin<2
B=A;
elseif ischar(B)&&strcmpi(B,'noself')
noself=true;
B=A;
end
N=size(A,1);
B=reshape(B,N,1,[]);
Graph=l2norm(bsxfun(@minus, A, B),1);
Graph=squeeze(Graph);
if noself
n=length(Graph);
Graph(linspace(1,n^2,n))=nan;
  7 个评论
Mazhar
Mazhar 2013-7-12
Say I have these values; x=[6 5.5 4 3 2 0 -2 -3 -4 -5 -5.5 -6 -5.5 -5 -4 -3 -2 0 2 3 4 5 5.5 6]; y=[0 2 3.5 4.5 5 5.5 6 5.5 5 4.5 3.5 2 0 -2 -3.5 -4.5 -5 -5.5 -6 -5.5 -5 -4.5 -3.5 -2 0]; How would I use your code to get the out put I want? Or how can I use a Loop for this!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by