0
$\begingroup$

The code

generate[matrix_] := Module[{n}, n := Dimensions[matrix][[1]];
                     Normal@Simplify@SparseArray[{
                     {i_, j_} /; i == 1 -> 2
                     }, {n, n}]]

a := {{1, 2}, {3, 4}}
generate[a]

produces

{{2, 2}, {0, 0}}

(of course there is no need to define the matrix a in the first place in this case). Now consider the modification

generate[matrix_] := Module[{n}, n := Dimensions[matrix][[1]];
                     Normal@Simplify@SparseArray[{
                     {i_, j_} /; i == 1 -> matrix[[i,j]]
                     }, {n, n}]]

a := {{1, 2}, {3, 4}}
generate[a]

where I only changed 2 into matrix[[i,j]]. Just like the first example generates a 2x2 matrix with zeros everywhere and fills in the first row with 2's, I would expect the second snippet of code to generate a matrix whose first row is the same as that of the input matrix a. Instead, I get the error message

Part: The expression i$ cannot be used as a part specification.

How would I go about solving this? Of course in this example I could just set each entry manually, but this example is just a proxy of the more complicated case I'm working with. I'm new to Mathematica. Thanks!

$\endgroup$
3
  • $\begingroup$ 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. $\endgroup$ Commented Oct 19, 2021 at 13:32
  • $\begingroup$ Use :> (RuleDelayed) instead of -> (Rule) to prevent evaluation of the matrix[[i,j]] part before i and j are substituted. $\endgroup$ Commented Oct 19, 2021 at 16:47
  • $\begingroup$ @LukasLang thanks!! $\endgroup$ Commented Nov 1, 2021 at 12:12

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.