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

조회 수: 6 (최근 30일)
Dario
Dario 2018년 4월 19일
답변: Geoff Hayes 2018년 4월 19일

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