matlabでオブジェクトの配列を操作するためにarrayfunを使う必要はありません。
[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配列を返します。最初の位置は最小値で、2番目の値はインデックスです。私はmatlab表記[~, idx]
を使用して、最初の戻り値には関心がなく、変数idx
に2番目の値を格納します。
私はそれだけをテストするために私の長方形のクラスを作成した例を書いたが、それは同様にあなたのクラスで動作します。以下は、私が定義したクラスのコードと、(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');