modify only the diagonal entries in a matrix?
91 次查看(过去 30 天)
显示 更早的评论
How can I Multiply the diagonal of a matrix by a number, for example; by 2?
0 个评论
采纳的回答
Jan
2018-7-9
编辑:Jan
2018-7-9
A = rand(4,3);
s = size(A);
index = 1:s(1)+1:s(1)*s(2); % Indices of the main diagonal
A(index) = A(index) * 2
This touches the elements on the diagonal only.
6 个评论
Alvin Chen
2021-6-21
@Image Analyst For loop would work for sure, but would it be more performable without using loop? Just extract the logicals by the positions of the indices in A.
Image Analyst
2021-6-21
I don't know what you mean by "performable". Sure there are other ways to perform this operation that may work, however I did not understand your explanation of extracting the logicals so I invite you to show your non-for loop way that doubles the values in the 4 diagonals in a non-square matrix, for example a 5 by 10 matrix.
m = ones(5, 10)
Please show us.
更多回答(1 个)
Image Analyst
2019-2-26
Here's a way you can do it using eye() to create indexes of the diagonal. I show two ways,
- one to create another output matrix and leave the input matrix alone, and
- another to change the input matrix in place.
% Create a logical mask for the diagonal elements.
d = logical(eye(size(m)))
% First way: Create an output matrix m2, retaining the original m.
m2 = m % Initialize with a copy of m
% Multiply diagonal elements of m2 (in place) by 2.
m2(d) = m(d) * 2 % Input values are replaced.
% Second way: Change/replace the values in original matrix.
% Multiply diagonal elements (in place) by 2.
m(d) = m(d) * 2 % Input values are replaced.
The two ways are the same except if you want a second matrix for the output you have to copy the input matrix first.
2 个评论
Jan
2019-2-26
At least in current Matlab versions:
d = eye(size(m), 'logical'); % faster than: logical(...)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!