# accessing and modifying matrix element

I basically want to do the following

A = Array[0 &, {4, 9}];
a = {2, 3};
A[[a[[1]], a[[2]]]] = 1;
A // MatrixForm


but with less cumbersome notation.(i.e. change line 3 to something nicer)!

I get the position as a pair (a list with 2 elements) and want to change the matrix entry at the position which that pair encodes. The pair is returned by the functions "RandomChoice" and "Position".

Thanks for the help!

• ReplacePart[A, a -> 1]? Nov 29, 2021 at 14:00
• ReplacePart[A, a -> 1] will create a new matrix that is what you want. You can assign that to A.
– Alan
Nov 29, 2021 at 14:01
• Welcome to Mathematica.SE! I hope you will become a regular contributor. To get started, 1) take the introductory tour now, 2) when you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge, 3) remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign, and 4) give help too, by answering questions in your areas of expertise. Nov 29, 2021 at 14:04
• SparseArray[{2, 3} -> 1, {4, 9}]; % // MatrixForm Nov 29, 2021 at 14:12
• Try: A[[Sequence @@ a]] = 1 Nov 29, 2021 at 16:22

This is my best interpretation of what the OP wants.

alist = RandomChoice[{"banana", "apple", "orange", "grapes"}, 9]

{"grapes", "orange", "orange", "banana", "orange", "orange", \
"grapes", "banana", "banana"}


Suppose the positions of "orange" have to be detected.

pos = Flatten@Position[alist, "orange"]


{2, 3, 5, 6}

A[[3, pos]] = 1
A // MatrixForm


$$\left( \begin{array}{ccccccccc} 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 1 & 0 & 1 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ \end{array} \right)$$

EDIT

Assuming that a pair of (valid) numbers is to be used to change the entry at that index to 13:

pos = {3, 8}  (* received from some function *)
A[[First@pos, Last@pos]] = 13
A // MatrixForm


$$\left( \begin{array}{ccccccccc} 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 1 & 0 & 1 & 1 & 0 & 13 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ \end{array} \right)$$

• What info? I just want to change line 3 in the example code I've given above. My problem: I have a matrix and a pair and I want to change the entry of the matrix corresponding to my pair. Nov 29, 2021 at 16:05
• Cool, thanks! I guess this is slightly more readable. Nov 29, 2021 at 16:17
• Thanks for the accept. @PeterMüller. The idea behind editing is that your post should be self-contained so that future visitors to the page should be able to read and understand the question without having to sift through the comments. See you later.
– Syed
Nov 29, 2021 at 16:21