modify only the diagonal entries in a matrix?
古いコメントを表示
How can I Multiply the diagonal of a matrix by a number, for example; by 2?
採用された回答
その他の回答 (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 件のコメント
Athikah Raihah
2019 年 2 月 26 日
Thanks a lot! That is very clear, exactly what I need!
Jan
2019 年 2 月 26 日
At least in current Matlab versions:
d = eye(size(m), 'logical'); % faster than: logical(...)
カテゴリ
ヘルプ センター および 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!