NEED HELP SOLVING "Array indices must be positive integers or logical values"
Show older comments
Im looking at a 3x3 grid around specific number within a larger 16x16 and in some cases i land up being outside of my 16x16 grind and therefore getting and error. Want i want to do is say if outside 16x16 grind then =0.
%new attempt (want to say if outside box then =0)
for i=a(1):a(256) %trying to calcule neighbours around each cell containing one
c=[a(i+1),a(i-1),a(i+16),a(i-16),a(i+15),a(i+17),a(-15),a(-17)]
c(isnan(c))=0
A(i)=c; %stores value as vector
end
Accepted Answer
More Answers (1)
Peter O
on 29 Aug 2020
Does it need to be a one-liner? If you can grab the x,y coordinate, you could clamp your index points to the box bounds using
% For a 256 x 256 grid
x_bounds = min(256, max(1, [index_x-16, index_x+16]))
y_bounds = min(256, max(1, [index_y-16, index_y+16]))
%Then get the 16x16 (or smaller) blob:
M = A(x_bounds(1):x_bounds(2),y_bounds(1):y_bounds(2))
You could do the same to clamp the 3x3 if it's near the edge of the image.
2 Comments
Daniel Hodgson
on 29 Aug 2020
Peter O
on 30 Aug 2020
Sorry for the delay and I see you've found a solution that works, and I think I misinterpreted your question at first because my solution wasn't what you wanted to do. However, to close the loop here:
Assuming you have a grid of 256x256 and you have an (x,y) position indictated by (index_x, index_y), this code will extract the square with a side length of 33 pixels around it and the (index_x,index_y) point at its center (16 pixels to either side). The minmax wrapping ensures that you never exceed the bounds of the grid 1...256. If you access something where the (index_x, index_y) is under 16 pixels from an edge, it clamps to the edge so you don't get an out-of-bounds error. If you were 8 pixels from the left edge and in the middle of the grid vertically, for instance (x,y) is (8, 50), you'd get a 24x33 region returned.
Categories
Find more on Images in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!