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

12 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by