3
$\begingroup$

How can i apply the Differences command to a list of matrices? I don't want to use a do cycle.

Do[ΔM[k] = M[[k]] - M[[k - 1]], {k, 1, Length[M]}]

I tried with Map, MapThread etc etc, but i don't get the result!!

$\endgroup$

1 Answer 1

4
$\begingroup$

Differences should work directly on your list of matrices, assuming that each matrix has the same dimensions. Compare its output with the more verbose Table equivalent:

SeedRandom[0];
M = RandomInteger[9, {5, 3, 3}];

Table[M[[k]] - M[[k - 1]], {k, 2, Length[M]}]

Differences[M]
{{{0, 2, -7}, {-2, 5, -4}, {-6, 8, 0}},
 {{-2, 3, 7}, {4, -1, 8}, {-2, -2, -6}},
 {{-5, 4, -5}, {1, 1, -2}, {6, 3, 6}},
 {{9, -5, -2}, {4, 1,  2}, {1, -2, -6}}}

{{{0, 2, -7}, {-2, 5, -4}, {-6, 8, 0}},
 {{-2, 3, 7}, {4, -1, 8}, {-2, -2, -6}},
 {{-5, 4, -5}, {1, 1, -2}, {6, 3, 6}},
 {{9, -5, -2}, {4, 1, 2}, {1, -2, -6}}}
$\endgroup$
2
  • $\begingroup$ Thanks, sometime I feel really stupid :) $\endgroup$
    – Kowalski
    Jan 19, 2017 at 7:05
  • $\begingroup$ @Kowalski You're welcome, and you shouldn't; operating over arrays is rather unusual from what I've seen and unless you've been using Mathematica (or APL or something) for years I think these "mistakes" are common. A related point: a number of functions operate on heads other than List even if they do not advertise that they do, e.g. Sort[foo[3, 1, 2]]. (Though that is in the Sort documentation.) Therefore it is often worth trying a function directly on a non-List expression to see what happens. $\endgroup$
    – Mr.Wizard
    Jan 19, 2017 at 16:56

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.