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

6 次查看(过去 30 天)

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 个评论
Jan
Jan 2018-4-19
编辑:Jan 2018-4-19
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?

请先登录,再进行评论。

回答(2 个)

Jan
Jan 2018-4-19
  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 2018-4-19

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.

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by