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

12 views (last 30 days)
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?

Answers (3)

John D'Errico
John D'Errico on 25 Oct 2018
Edited: John D'Errico on 25 Oct 2018
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 on 24 Oct 2018
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 on 25 Oct 2018
max(a21(:),a21(:)').^2 .* (ones(5) - 2*eye(5));

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!