您不需要使用arrayfun來操作matlab中的對象數組。還有用於獲取屬性數組出對象的數組的一個非常有用的速記:
[rectangles.minx]
國債收益率所有矩形的minx
在數組中。因此,要知道哪一點最接近原點,我會計算出與原點的良好歐裏距離。隨着矢量在手,這是真的簡單。
的歐幾里德距離被定義爲如下:
d(a,b) = sqrt((a.x - b.x)^2 + (a.y - b.y)^2);
與您的矢量來計算它:
distances = sqrt([rectangles.minx].^2 + [rectangles.miny].^2)
這將產生一個矢量與所有點的距離。找到最小值是微不足道的:
[〜,idx] = min(距離);
min函數返回一個1x2數組,第一個位置是最小值,第二個是索引。我用matlab符號[~, idx]
來說明我對第一個返回值不感興趣,第二個應該存儲在變量idx
上。
我已經寫了一個例子,其中我創建了我的矩形類來測試它,但它也適用於您的類。以下是我定義的類的代碼和計算最接近(0,0)的點的代碼。
運行它的想法玩,使其適應您的需求:)
測試類定義(保存在一個名爲Rectangle.m文件):
classdef Rectangle
properties
minx;
miny;
end
methods
function obj = Rectangle(v1,v2)
if nargin > 1
obj.minx = v1;
obj.miny = v2;
end
end
end
end
代碼
clear all;
numRect = 100;
rect_array = Rectangle(numRect);
% initialize rectangles
for n=1:numRect
r = Rectangle;
r.minx = 100*rand(1,1);
r.miny = 100*rand(1,1);
rect_array(n) = r;
end
% find point closest to the origin
[~, idx] = min(sqrt([rect_array.minx].^2 + [rect_array.miny].^2));
close all;
figure;
% plot the points in blue
plot([rect_array.minx],[rect_array.miny],'b.');
hold on;
% mark a red cross on the point closest to the origin
plot(rect_array(idx).minx, rect_array(idx).miny, 'rx');