Group Abstract Group Abstract

Message Boards Message Boards

0
|
3.6K Views
|
2 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Change the diagonal elements of a matrix

Posted 3 years ago

I have the matrix m:

m={
{47, 17, 23},
{14, 24, 36},
{47, 31, 23}
}

I want to change the elements on its diagonal to {100,200,300}.

The solution I have for that now is

Table[m〚i,i〛= {100,200,300}〚i〛
, {i, 1, Length[m]}]

I am sure there is a nicer way to do that, but I can't think of any.

Can anyone give me a hint?

POSTED BY: Ehud Behar
2 Replies
Posted 3 years ago

An alternative with ReplacePart

m = {{47, 17, 23}, {14, 24, 36}, {47, 31, 23}};
v = {100, 200, 300};

ReplacePart[m, Thread[Table[{i, i}, {i, 3}] -> v]]
POSTED BY: Hans Milton
Posted 3 years ago

Nicer is likely subjective.

One other way of doing this comes from the Applications section of the documentation for DiagonalMatrix.

replaceDiagonal[m_,v_]:=m-DiagonalMatrix[Diagonal[m]-v];
m={{47, 17, 23},{14, 24, 36},{47, 31, 23}}; v={100,200,300};
replaceDiagonal[m,v]
POSTED BY: Bill Nelson
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard