MATLAB: How to extract values in a specific area of the matrix

centerlocate

In my particular case, I have a 6 x 8 matrix and the assignment is asking me to locate the four values closest to the center of the matrix.I figured there's a command for this purpose rather than manually finding the center.

Best Answer

A = rand(6,8) ;
[nx,ny] = size(A) ;
[r,c] = meshgrid(1:ny,1:nx) ;
C = round([nx ny]/2) ;
idx = knnsearch([r(:) c(:)],C,'k',4) ;
iwant = A(idx)