フィルターのクリア

How to multiply all values in the diagonal of a matrix by -1 in Matlab?

12 ビュー (過去 30 日間)
Augustin Cheeley
Augustin Cheeley 2018 年 10 月 24 日
回答済み: Andrei Bobrov 2018 年 10 月 25 日
Hello, my code for my matrix is as follows c3 = tril((repmat(a21,[5 1]))'.^2, -1) + triu((repmat(a21,[5 1])).^2) where a21 is just the vector 1:1:5. so my matrix c3 is a 5x5 matrix with all positive elements. I am trying to make just the elements in the diagonal of c3 negative. How can I do this by changing my line of code in matlab?

回答 (3 件)

John D'Errico
John D'Errico 2018 年 10 月 25 日
編集済み: John D'Errico 2018 年 10 月 25 日
A bit simpler than what you did is...
A = max(a21,a21').^2;
A(1:6:end) = -A(1:6:end);
A
A =
-1 4 9 16 25
4 -4 9 16 25
9 9 -9 16 25
16 16 16 -16 25
25 25 25 25 -25
with no loop required. It does require at least R2016b though to work. It should be doable in one line of code too, but sometimes the extra effort just makes for unreadable code too.
Sigh. You insist on a one-liner? ;-) I suppose this works.
A = toeplitz([-1 1 1 1 1]).*max(a21,a21').^2;
but it would help to know what toeplitz does. As it is, if you are not familiar with toeplitz, then the latter form I wrote tends to look rather strange.
In either case, it is pretty simple to fix in the case where a21 is some vector of completely arbitrary length.

Erivelton Gualter
Erivelton Gualter 2018 年 10 月 24 日
Hi Augustin,
This may help you
a21 = 1:1:5;
c3 = tril((repmat(a21,[5 1]))'.^2, -1) + triu((repmat(a21,[5 1])).^2);
for i=1:5
c3(i,i) = -c3(i,i);
end

Andrei Bobrov
Andrei Bobrov 2018 年 10 月 25 日
max(a21(:),a21(:)').^2 .* (ones(5) - 2*eye(5));

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by