UPD: 更新前是C++...更新后希望有点matlab的样子了...
Part 6. Problem 51 - Problem 60.
Problem 51. Find the two most distant points
% Given a collection of points, return the indices of the rows that contain the two points most distant from one another. The input vector p has two columns corresponding to the x and y coordinates of each point. Return ix, the (sorted) pair of indices pointing to the remotest rows. There will always be one unique such pair of points.
%
% So if
%
% p = [0 0]
% [1 0]
% [2 2]
% [0 1]
%
% Then
%
% ix = [1 3]
%
% That is, the two points p(1,:) and p(3,:) are farthest apart.
function ix = mostDistant(p)
mxdis = 0; ix = [1 2];
sp = size(p);
for k = 1:sp(1)
for l = (k+1):sp(1)
dist = sqrt((p(k,1)-p(l,1))^2+(p(k,2)-p(l,2))^2);
if dist > mxdis
mxdis = dist;
ix(1) = k;
ix(2) = l;
end
end
end
UPD: 可以用dist, triu函数改写成这样.
function idx = mostDistant(p)
p = triu(dist(p'));
[r c] = find(p == max(p(:)));
idx = [r c];
triu(A), 取矩阵A的上三角矩阵,其余置为0.
Problem 52. What is the next step in Conway's Life?
function B = life(A)
B = A;
rmove = [-1 -1 -1 0 1 1 1 0];
cmove = [-1 0 1 1 1 0 -1 -1];
sa = size(A);
for r = 1:sa(1)
for c = 1:sa(2)
cnt = 0;
for k = 1:8
g = r + rmove(k); h = c + cmove(k);
if g < 1 g = g + sa(1); elseif g > sa(1) g = g - sa(1); end
if h < 1 h = h + sa(2); elseif h > sa(2) h = h - sa(2); end
cnt = cnt + A(g, h);
end
if A(r, c) == 1
if cnt < 2 || cnt > 3
B(r, c) = 0;
end
else