2

Suppose I have this kind of matrix:

1 2 3
3 2 3
4 5 6
7 8 9
3 2 3

How do I add a diagonal of ones into this? Is there an easy way? To show what I mean:

1 2 3
3 1 3
4 5 1
1 8 9
3 1 3
Daniel
  • 36,610
  • 3
  • 36
  • 69
Paulinchen2
  • 125
  • 1
  • 6

4 Answers4

5

You can do this quite easily with linear indexing, you don't even need reshape!

[r, c] = size(m);
m(1:c:end) = 1;
m =

     1     2     3
     4     1     6
     7     8     1
     1    11    12
    13     1    15

If r < c, this is the best I got:

if r < c
   n = m';
   n(1:r:end) = 1;
   m = n';
else
   m(1:c:end) = 1;
end
Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70
  • @jkshah: Honestly, I can't find a way to do that *and* avoid `if` using just linear indexing. I updated the answer. If you have a better suggestion, *shoot*! =) – Stewie Griffin Nov 14 '13 at 20:02
  • 1
    @RobertP. +1. seems perfect! I didn't have better solution, but was trying to make it complete. Appreciate your thinking. – jkshah Nov 15 '13 at 05:10
  • @RobertP. You don't even need the row number: why not just `m(1:size(m,2):end) = 1`? Note, however, that your solution only works for r >= c – Luis Mendo Nov 15 '13 at 12:18
2

This is a general solution, using linear indexing and modulo operations:

[R C] = size(m);
ii = 1:R;
jj = mod(ii,C);
jj(jj==0) = C;
m(ii+(jj-1)*R) = 1; %// or m(sub2ind([R C],ii,jj)) = 1;

For example,

m =

     1     2     3
     4     5     6
     7     8     9
    10    11    12
    13    14    15
    16    17    18
    19    20    21

gets transformed into

m =

     1     2     3
     4     1     6
     7     8     1
     1    11    12
    13     1    15
    16    17     1
     1    20    21
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
0
s=min(size(m))
m(1:s,1:s)=eye(s)+(~eye(s).*m(1:s,1:s))
Daniel
  • 36,610
  • 3
  • 36
  • 69
0

If you want a shorter version without comparing the number of rows to the number of columns you can try this (Assuming that you want to make the diagonal elements of an arbitrary matrix M equal to 1):

M(logical(speye(size(M)))) = 1 
Chris
  • 460
  • 2
  • 12