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] %
Dan
  • 45,079
  • 17
  • 88
  • 157
cenging
  • 3
  • 1
  • 2

1 Answers1

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
Dan
  • 45,079
  • 17
  • 88
  • 157
  • Hello dan, This change only 1 diagonal in matrix, I want to change all diagonals in matrix. – cenging Mar 28 '13 at 09:39
  • 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. – Dan Mar 28 '13 at 09:55
  • 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) – Dan Mar 28 '13 at 11:39