Use eye
function to get an identity matrix and add to original matrix
result = A+eye(3,3) ; % A the original matrix
سؤال
I have a matrix such as
[1 1 1
1 1 1
1 1 1]
I want it to be
[2 1 1
1 2 1
1 1 2]
How do I do that?
المحلول
Use eye
function to get an identity matrix and add to original matrix
result = A+eye(3,3) ; % A the original matrix
نصائح أخرى
Another possibility, which requires less operations (may be better for large matrices):
A(1:size(A,1)+1:end) = A(1:size(A,1)+1:end) + 1;
This uses the concept of linear indexing to address the diagonal elements.
Yet another way via logical indexing:
idx = eye(size(A))>0;
A(idx)= A(idx)+1;
This can easily be used for other things as well:
A(~idx)=2*A(~idx); %Multiply all non diagonal elements by two
A(eye(size(A))>0)=1:min(size(A)); %Set the diagonal to 1:n