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
Shai
  • 111,146
  • 38
  • 238
  • 371
Larry Foobar
  • 11,092
  • 15
  • 56
  • 89

1 Answers1

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.

Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371
  • 1
    Heh, it was just so simple! Thanks. P.S. Yeah, I've corrected my code – Larry Foobar Aug 06 '14 at 08:08
  • 1
    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](http://stackoverflow.com/a/14861015/2903371). Otherwise nice code +1 – patrik Aug 06 '14 at 09:00
  • @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](http://stackoverflow.com/questions/25150027/using-transpose-versus-ctranspose-in-matlab). – Shai Aug 06 '14 at 09:06
  • @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 – patrik Aug 06 '14 at 09:26