0

I am interesting to replace the diagonal of matrix D to 1,2,3,4. This is matrix D:

A=[1,2,3,4,2,3,4,5; 3,4,5,6,4,5,6,7]; D=[A;A]; D=[D D]; % size of matrix [4x16] % 
2
  • 2
    what do u mean by the diagonal? D is a non-square matrix.. Commented Mar 28, 2013 at 9:05
  • @Kishore, a main diagonal is also defined for non-square matrices. Commented Mar 28, 2013 at 9:15

1 Answer 1

2

To set the main diagonal to integers starting a 1 and incrementing by 1:

D(eye(4)==1) = 1:4 

Or to generalize it:

n = min(size(D)); D(eye(n)==1) = 1:n; 

note here that the ==1 is to convert the output of eye(n), the identity matrix, to type logical.

EDIT:

This is just a guess at what you mean by all the diagonals but here goes:

n = size(D,1); m = size(D,2); I = repmat(eye(min([n,m])), ceil(n/m), ceil(m/n)); I = I(1:n, 1:m)==1 d = repmat(1:min([n,m]), 1, max([ceil(n/m), ceil(m/n)])); d = d(1:max(m,n)); D(I) = d 
Sign up to request clarification or add additional context in comments.

3 Comments

Hello dan, This change only 1 diagonal in matrix, I want to change all diagonals in matrix.
What other diagonals? Please provide a manually calculated example and add it to your question (edit your original question) so we can see what you mean.
No problem, please mark the answer as correct and upvote if you found it helpful (by clicking the arrow and the tick in the top left of this answer)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.