2

I have a binary image with some objects, and I want to get some characteristics of these objects.

I = imread('coins.png');
B = im2bw(I, 100/255); B = imfill(B, 'holes');

RP = regionprops(B, 'Area', 'Centroid');

RP becomes a structure array:

10x1 struct array with fields:
    Area
    Centroid

I need to make from this structure 2 arrays called Areas and Centroids. How to make it without loops?

Using loops we can go this way:

N = numel(RP);
Areas = zeros(N, 1); Centroids = zeros(N, 2);
for idx=1:N, 
    Areas(idx) = RP(idx).Area; 
    Centroids(idx, :) = RP(idx).Centroid; 
end

1 Answer 1

4

You can simply concat

Areas = [RP.Area];
Centroids = vertcat( RP.Centroid );

PS,
It is best not to use i as a variable name in Matlab.

Sign up to request clarification or add additional context in comments.

4 Comments

Heh, it was just so simple! Thanks. P.S. Yeah, I've corrected my code
These day I do not think that i or j will have a large impact in terms of runtime or overhead. Also 1i or 1j is the proper way to denote the imaginary number. If you write code yourself, make sure to always use 1i and if you work on a company, there should be praxises in this matter. Ofcourse it may be error prone to use i as a variable, but personally I have nothing against it. Unless you can show somedence that using i as a loop variable slows the performance significantly I would say it is matter of taste. Otherwise nice code +1
@patrik I agree that avoiding using i as a variable is more of a good practice than a "must", but we are trying to promote better practices here. See e.g., this recent post.
@Shai If it is good practice or not to avoid using i is highly dependent of what you are used to do. A person with experience from some other programming language (which does not use i as complex number) may have used i as a looping variable of his life. For nested loops, he may even have used a special set of looping variables i,j,k,... to keep track of which loop he is in for the moment. In that case I would say it is a bad practice to change this behaviour. The person in question will almost certainly slip in a i in some loop just to wonder why when he see the code again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.