2

What is the best way to get the element of a list, which is computed out of substituded variables?

For example one wants to get the first element of the first row of

 (a A + a B) /. {a -> 2, A -> {{1, 2}, {3, 4}}, B -> {{8, 7}, {6, 5}}}

Using

 (a A + a B)[[1,1]] /. {a -> 2, A -> {{1, 2}, {3, 4}}, B -> {{8, 7}, {6, 5}}}

gives me:

2

I tried something like

elem[x_?MatrixQ, part__: All] := x[[part]];

But this makes the result only more disturbing...

This result should be able to be used in an other expression, where the substituion is done: For example:

temp = (a A+a B)[[1,1]];
temp + 3 /. {a -> 2, A -> {{1, 2}, {3, 4}}, B -> {{8, 7}, {6, 5}}}

Last but not least: Is there also a possibility to hold other expressions? For Example:

temp1[x_] := (x a A + a B)[[1,1]] // Hold;
temp2 = NIntegrate[temp1[x],{0,1,x}] // Hold;
temp2 + 3 /. {a -> 2, A -> {{1, 2}, {3, 4}}, B -> {{8, 7}, {6, 5}}} // ReleaseHold

?

Matthias
  • 21
  • 2
  • @Kuba the result should be $2\cdot 1+2\cdot 8=18$ – Matthias Oct 17 '14 at 15:35
  • Without the factor $a$ mathematica gives the expected result $9$. But with a warning message. – Matthias Oct 17 '14 at 15:38
  • @Kuba Unfortunately I can not use your solution, because expression $(a A + a B)[[1,1]]$ is done inside a function, where the substitution not done. – Matthias Oct 17 '14 at 15:43
  • @Kuba Look at the last example. How to write the first line to use $temp$ in a way like the second line. Without $a$ this would work fine. – Matthias Oct 17 '14 at 15:47
  • temp = Hold[(a A + a B)[[1, 1]]]; temp + 3 /. {a -> 2, A -> {{1, 2}, {3, 4}}, B -> {{8, 7}, {6, 5}}} // ReleaseHold ? – Kuba Oct 17 '14 at 15:51
  • @Kuba Thanks! This looks like what I was looking for! – Matthias Oct 17 '14 at 15:53

3 Answers3

2
exp = (a A + a B) /. {a -> 2, A -> {{1, 2}, {3, 4}}, 
   B -> {{8, 7}, {6, 5}}};
exp[[1, 1]]

The original code takes part [[1,1]] of the expression which is a, hence 2. Alternatively you could put parentheses around expression and rules and take part or

Part[(a A + a B) /. {a -> 2, A -> {{1, 2}, {3, 4}}, 
   B -> {{8, 7}, {6, 5}}}, 1, 1]
ubpdqn
  • 60,617
  • 3
  • 59
  • 148
1

Since V10 you can play with Inactivate and Activate

x = a A + a B /. {a -> 2, A -> {{1, 2}, {3, 4}}, B -> {{8, 7}, {6, 5}}} // Inactivate;

x[[1]]

enter image description here

x[[2]]

enter image description here

y = Activate[x, ReplaceAll]

enter image description here

z = Activate[y]

{{18, 18}, {18, 18}}

z[[1, 1]]

18

Or, directly

Activate[x][[2, 2]]

18

eldo
  • 67,911
  • 5
  • 60
  • 168
0

I don't know why you believe your elem function does not work as it is just how I would approach this and it works as expected:

elem[x_?MatrixQ, part__: All] := x[[part]];

elem[(a A + a B), 1, 1] /. {a -> 2, A -> {{1, 2}, {3, 4}}, B -> {{8, 7}, {6, 5}}}
18
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371