# Efficient method to set Matrix values based on position [closed]

I have a matrix, a list of positions, and a vector.

I want a new matrix with the values of the vector inserted into the original matrix based upon the list of positions.

For example:

oldMatrix = {{a1, a2, a3, a4}, {b1, b2, b3, b4},
{c1, c2, c3, c4}, {d1, d2, d3, d4}};

positions = {{1, 1}, {2, 3}, {3, 2}, {4, 1}}

newElements = {A1, B3, C2, D1}

Then I want the new matrix to be

If I was working with a vector rather than a matrix this would be easy:

newVector = oldVector
newVector[[{positions}]] = newElements

as vectors support a list when indexing.

This will not work with matrices.

I have searched and read with interest this answer but it doesn’t fit this problem.

The best I have been able to come up with is:

setMatrix[matrix_, positionsMatrix_, vector_] := Module[
{
vectorF,
positionsVector,
row,
column
},

vectorF = Flatten[matrix];
{row, column} = Dimensions[matrix];

positionsVector = Map[(#[[1]] – 1)*row + #[[2]] &,
positionsMatrix];

vectorF[[positionsVector]] = vector;

Partition[vectorF, row]
]

but I would hope there was a simpler, more elegant and efficient approach.

=================

=================

1

=================

oldMatrix = {{a1, a2, a3, a4}, {b1, b2, b3, b4}, {c1, c2, c3,
c4}, {d1, d2, d3, d4}};

positions = {{1, 1}, {2, 3}, {3, 2}, {4, 1}};

newElements = {A1, B3, C2, D1};

(newMatrix =
ReplacePart[oldMatrix,