HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Using the Return Value of a Function to Select an Element in a Struct Array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thestructreturnarrayfunctionvalueusingelementselect

Problem

I'm learning MATLAB (still trying to "think in vectors") and have the following piece of code:

stats = regionprops(bwconncomp(mask), 'all');

% find the object nearest our nucleus
smallest_dist = flintmax;
location = [cell_x, cell_y];
for j = 1:numel(stats)
    stat = stats(j);
    dist = pdist([location;[stat.Centroid]], 'euclidean');
    if dist < smallest_dist
        regions{channel} = stat; 
        smallest_dist = dist;
    end
end


All that is doing is searching through a struct array for the region which has a location (centroid) closest to my known cell's X/Y. I'm sure this is not canonical and that it could be improved.

Solution

I think this comes pretty close. The use of arrayfun() or other *fun()-Operations is very often better than for loops.

Your code was not working out of the box. Thus, I created code, which is directly executable:

function minimalExample()
    target.x = 10;
    target.y = 5;

    source(1) = struct('x', 1, 'y', 3);
    source(2) = struct('x', 5, 'y', 15);

    [~, minIndex] = min(arrayfun(@(x) (myDistance(x, target)), source));

    minSource = source(minIndex);
    disp(minSource);

    function d = myDistance(source, target)
        d = (source.x - target.x)^2 + (source.y - target.y)^2;
        d = sqrt(d);
    end
end

Code Snippets

function minimalExample()
    target.x = 10;
    target.y = 5;

    source(1) = struct('x', 1, 'y', 3);
    source(2) = struct('x', 5, 'y', 15);

    [~, minIndex] = min(arrayfun(@(x) (myDistance(x, target)), source));

    minSource = source(minIndex);
    disp(minSource);

    function d = myDistance(source, target)
        d = (source.x - target.x)^2 + (source.y - target.y)^2;
        d = sqrt(d);
    end
end

Context

StackExchange Code Review Q#49776, answer score: 2

Revisions (0)

No revisions yet.