採用された回答

Jan
Jan 2018 年 7 月 9 日
編集済み: Jan 2018 年 7 月 9 日

1 投票

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 件のコメント

Athikah Raihah
Athikah Raihah 2019 年 2 月 25 日
I would like to keep A and display the new modified matrix as A1. Could you please show me how?
Image Analyst
Image Analyst 2019 年 2 月 26 日
A1 = A; % Initialize
A1(index) = A(index) * 2 % Multiply diagonal by 2
Alvin Chen
Alvin Chen 2021 年 6 月 21 日
編集済み: Alvin Chen 2021 年 6 月 21 日
Does not work well on non-square matrices, e.g. MxN, N > M.
Image Analyst
Image Analyst 2021 年 6 月 21 日
編集済み: Image Analyst 2021 年 6 月 21 日
@Alvin Chen, a trivial for loop will work fine. For the upper left diagonal:
[rows, columns] = size(A);
n = min([rows, columns]);
for k = 1 : n
A(k, k) = A(k, k) * 2;
end
You can use a similar loop for the three other diagonals.
Alvin Chen
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
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
Image Analyst 2019 年 2 月 26 日

3 投票

Here's a way you can do it using eye() to create indexes of the diagonal. I show two ways,
  1. one to create another output matrix and leave the input matrix alone, and
  2. 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
Athikah Raihah 2019 年 2 月 26 日
Thanks a lot! That is very clear, exactly what I need!
Jan
Jan 2019 年 2 月 26 日
At least in current Matlab versions:
d = eye(size(m), 'logical'); % faster than: logical(...)

サインインしてコメントする。

カテゴリ

ヘルプ センター および File Exchange で Operating on Diagonal Matrices についてさらに検索

質問済み:

2018 年 7 月 9 日

コメント済み:

2021 年 6 月 21 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by