# How can I extract the numbers divisible by 3 from the diagonal of a nxn matrix composed of random integers?

조회 수: 17(최근 30일)
João 2022년 10월 27일
댓글: João 2022년 10월 27일
I can create a random matrix of nxn with integers in [100;1000] interval, for example:
n=input('Choose the number of lines and columns of the square matrix: ')
A=randi([100,1000], n, n)
D=diag(A)
So the numbers in D are the numbers from the main diagonal of A. Now I would like to extract the numbers in D that are divisible by 3 and create matrix with those numbers, how can i do this?

댓글을 달려면 로그인하십시오.

### 채택된 답변

KALYAN ACHARJYA 2022년 10월 27일
n=input('Choose the number of lines and columns of the square matrix: ')
A=randi([100,1000], n, n)
D=diag(A)
mat=D(mod(D,3)==0)
##### 댓글 수: 1표시숨기기 없음
João 2022년 10월 27일
Thank you, that works perfectly!

댓글을 달려면 로그인하십시오.

### 범주

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

R2021a

### Community Treasure Hunt

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

Start Hunting!

Translated by