# Matlab: select a portion of a matrix

The following script gives me the error "Subscript indices must either be real positive integers or logicals."

I do not understand why, since the vars are integers. Moreover, I also cast them to integers.

The code is:

``````x_start = int16(x-matrixRay);
x_end = uint16(x+matrixRay);
y_start = uint16(y-matrixRay);
y_end = uint16(y+matrixRay);
matrix = img(x_start:x_end,y_start:y_end);
``````

I put a breakpoint just before the code above. Below I list the values of the variables:

``````    K>> x_start

x_start =

uint16

298

K>> x_end

x_end =

uint16

302

K>> y_start

y_start =

uint16

88

K>> y_end

y_end =

uint16

92

K>> matrixRay

matrixRay =

2
``````

Clearly I cannot post all the matrix "img", since it is pretty big. The workspace it is a 1369x1173 uint8.

As others have pointed out, int8 (-128 to 127) clearly won't cover your image size. Given the size, you may use uint16 for index. It doesn't make much sense to use signed integer for indexing. You may simply use round to create index in case it could be non-integer.

But int8 just gives you wrong result (worse than error in my opinion). The error you got is because your x_start or y_start is zero. You can check this easily by setting up a breakpoint.

If you are sure what you are doing is what you want, you may fix the problem like this:

``````x_start = round(x-matrixRay); % or uint16 if size is less than 2^16
x_start = max(x_start, 1); % use 1 if less than 1
x_end = round(x+matrixRay);
x_end = min(x_end, size(img,1)); % clip to max of img size
``````

The similar should be applied to y_start and y_end.