Question

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
Was it helpful?

Solution

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

OTHER TIPS

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
s=min(size(m))
m(1:s,1:s)=eye(s)+(~eye(s).*m(1:s,1:s))

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 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top