2012-04-07 56 views
3

如果這是一個愚蠢的問題,我很抱歉,我對Matlab比較陌生。從對象數組中獲取最小屬性值

我有一個類矩形矩陣的數組,其屬性minx, miny, maxx, maxy,它們表示角座標。

我想要獲取數組中的左上角矩形的索引。

我可以通過對象循環來獲得對應於最小x和y座標的對象,但這看起來不像一個非常matlabic(matlabian?聽起來不像pythonic那麼好)的方式它。

minx = -1 
miny = -1 
tl_rect_id = 0 

for id = 1:num_objects 
    if ((rectangles(id).minx < minx || minx == -1) && (rectangles(id).miny < miny || miny == -1)) 
     tl_rect_id = id 
     minx = rectangles(id).minx 
     miny = rectangles(id).miny 

    end 

    % plot coordinates of top left corners 
    plot(rectangles(id).minx,rectangles(id).miny,'+r') 
end 

回答

4

您不需要使用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'); 
2

您的代碼是找到更遠的矩形或最遠的矩形。如果你不擔心具有瘋丫頭相同值的多個外接矩形框,你可以做

[v i] = min(arrayfun(@(i)rectangles(i).minx, 1:num_objects)) 
fprintf('Furthest left rectangle is %g\n', i); 

或者,你可以這樣做:

[v i] = sortrows(cell2mat(arrayfun(@(i)[rectangles(i).minx; rectangles(i).miny], 1:num_objects, 'uniformoutput', 0))'); 
fprintf('Furthest left rectangle is %g\n', i(1)); 

將由X進行排序,然後Y,然後在這次訂購中取得第一名。這比較慢,因爲它有一種排序。爲了得到上述算法的確切行爲,你應該堅持使用for循環,我認爲簡潔的做法會很麻煩。