Apologies if this is a stupid question, I’m relatively new to Matlab.
I’ve got an array of rectangles of class Rectangle with properties minx, miny, maxx, maxy, which represent the corner coordinates.
I’m trying to get the index of the top-left rectangle in the array.
I can loop through the objects to get the object that corresponds to the minimum x and y coordinates, but this doesn’t seem like a very matlabic (matlabian? doesn’t sound nearly as good as pythonic) way to do it.
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
You don’t need to use arrayfun to operate on arrays of objects in matlab. There’s a very useful shorthand for getting an array of properties out of an array of objects:
That yields all rectangle’s
minxin an array.So to know which is the point closest to the origin, I would calculate the good ol’ euclidean distance to the origin. With the vectors at hand, that’s REALLY simple.
The euclidean distance is defined as follows:
to calculate it with your vectors:
This will yield a vector with the distances of all points. Finding the minimum is trivial:
[~, idx] = min(distances);
The min function returns a 1×2 array, the first position is the minimum value, the second is the index. I’ve used the matlab notation
[~, idx]to state that I’m not interested in the first return value, and the second should be stored on the variableidx.I’ve written an example in which I have created my rectangle class only to test it, but it will work with your class as well. Below are the codes for the class I’ve defined and the code that calculates the point closest to (0,0).
Run it to play with the idea and adapt it to your needs 🙂
Test Class definition (save that in a file called Rectangle.m):
Code