Search code examples
arraysimagematlabloopscentroid

Updating a struct with new values in a for loop


My image array: C_filled = 256x256x3270

What I would like to do is calculate the centroids of each image, and store each centroid corresponding to each 'slice'/image into an array. However, when I try to update the array, like a regular array, I get this error:

"Undefined operator '+' for input arguments of type 'struct'."

I have the following code:

for i=1:3270;

cen(i) = regionprops(C_filled(:,:,i),'centroid');

centroids = cat(1, cen.Centroid);% convert the cen struct into a regular array.

cen(i+1) = cen(i) + 1; <- this is the problem line

end

How can I update the array to store each new centroid?

Thanks in advance.


Solution

  • That's because the output of regionprops (i.e. cen(i)) is a structure, to which you try to add the value 1. But since you try to add the value to the structure and not one of its field, it fails.

    Assuming that each image can contain multiple objects (and therefore centroids), it would be best (I think) to store their coordinates into a cell array in which each cell can be of a different size, contrary to a numeric array. If you have the exact same number of objects in each image, then you could use a numeric array.

    If we look at the "cell array" option with code:

    %// Initialize cell array to store centroid coordinates (1st row) and their number (2nd row)
    centroids_cell = cell(2,3270);
    
    for i=1:3270;
    
    %// No need to index cen...saves memory
    cen = regionprops(C_filled(:,:,i),'centroid');
    
    centroids_cell{1,i} = cat(1,cen.Centroid);    
    centroids_cell{2,i} = numel(cen.Centroid);
    
    end
    

    and that's it. You can access the centroid coordinates of any image using this notation:centroids_cell{some index}.