This is unclear. An image does not have a neighboring pixel. A pixel in an image will have 8 neighbors, but the image as a whole does not.
And your subject (whatever it means) does not match the body of your question. "randomly choose the pixels value" is not grammatically correct. It makes a difference if "pixels" is plural, or if you meant "pixel's" meaning possessive.
You might mean that pixels have values from 0 to 255 and that you want to choose one of those integer values. For example, return 169 regardless of whether any particular pixel in the image has that value.
Or you might mean that given some randomly chosen set of pixels, extract one value from the set of values that those pixels have. For example, you chose 3 pixels with the values 30, 100, and 142 and you choose 142 at random from those 3 values.
Or maybe you mean some kind of combination of your subject line and one interpretation of your body. You might mean that you choose some number of pixels at random locations (say it's 3) and you want all of the values that those pixels have. For example you return 30, 100, 142 (_all_ of them, not just one of them).
Perhaps you can use randperm() to select pixel locations:
randomPixelIndexes = randperm(numel(yourImage), numberOfPixelsToReturn); randomPixelValues = yourImage(randomPixelIndexes);
Why don't you share the intent of this process so we can see if this is even the best approach? Or post your image and tell us what you want to measure or do with it?
switch randi(8,1,1) case 1: rpix = YourImage(i-1,j-1); case 2: rpix = YourImage(i-1,j); case 3: rpix = YourImage(i-1,j+1); case 4: rpix = YourImage(i,j-1); case 5: rpix = YourImage(i,j+1); %skip i,j as that is the pixel itself case 6: rpix = YourImage(i+1,j-1); case 7: rpix = YourImage(i+1,j); case 8: rpix = YourImage(i+1,j+1); end