How can I put in an array the elements near the center?

8 views (last 30 days)

I have a matrix 100x100. I want to save the 8 elements around the center of the matrix in an array. Then I want to save the 16 elements around the 8 elements and so on till I finish the matrix.

 + + + + +
 + - - - +
 + - + - +
 + - - - +
 + + + + +

Explaining it in a better way, I want to save the '+' in the middle in an array. Then, I want to save all the '-' in another array. Finally I want to save all the '+' in a third array. And so on till I complete the 100x100 matrix (that I attached).

Thanks in advance.

  1 Comment
Jan
Jan on 19 Apr 2018
Edited: Jan on 19 Apr 2018
What is your question? In a 100x100 (or any other even number) matrix, there is no element in the center. So which element do you want to choose? What have you tried so far?

Sign in to comment.

Answers (2)

Jan
Jan on 19 Apr 2018
  1. Decide for a method to define exactly, which is the "center" in a matrix with an even side length.
  2. Create a for loop from 0 to the half side length
  3. Then 4 for loops use the value from the first loop to collect the elements.
  4. Store the elements in a cell array.

Geoff Hayes
Geoff Hayes on 19 Apr 2018

Dario - you could create a recursive function that "peels" off the outer "layer" of your input matrix. You would then pass a subset of the initial matrix (less the first row, first column, last row, and last column) into your function to get peel off the next "layer". You would continue in this matter until either the input matrix is empty (implying that your initial square matrix has an even number of rows/columns) or is a scalar (implying that your initial square matrix has an odd number of rows/column). The algorithm might be something like

  1. If matrix is empty then return empty cell.
  2. If matrix is scalar then return cell containing matrix (centre).
  3. If matrix has the same number of rows and columns, then peel off the outer layer (first row, last row, first column, second column) and save as array in a cell. Concatenate this cell with the output of your call to the recursive function passing in your matrix less the "layer" that you peeled away.

Categories

Find more on Multidimensional Arrays 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!