4
$\begingroup$

Suppose I have a list of matrices $(A,B,C)$ and a vector $v$. I want to construct a table whose elements are sequential applications of these matrices to $v$, i.e., the first entry will be $Cv$, the second will be $BCv$, and the third is $ABCv$. An efficient way to do this should be to compute a single matrix product for each table entry; for example, after storing the second entry in the above example, I don't need to compute $BC$ to $v$ again, I just need to apply $A$ to $BCv$.

To me the natural way to code this is to use loops to iteratively define the table elements, but my understanding is that this is slow in Mathematica. How can I solve this problem, and more generally, make tables from sequential applications of an operation rather than writing down a formula in the usual table syntax?

$\endgroup$
1
  • 3
    $\begingroup$ FoldList[#2 . #1 &, v, {C, B, A}] $\endgroup$ Mar 26 at 16:22

1 Answer 1

7
$\begingroup$

This can be accomplished using FoldList.

Clear[f, a, b, c, amat, bmat, cmat, v]
FoldList[#2 . #1 &, v, {cmat, bmat, amat}]

{v, cmat . v, bmat . cmat . v, amat . bmat . cmat . v}


Test:

amat = RandomReal[1, {3, 3}];
bmat = RandomReal[1, {3, 3}];
cmat = RandomReal[1, {3, 3}];
v = RandomReal[1, 3];


MatrixForm /@ {v, cmat . v, bmat . cmat . v, amat . bmat . cmat . v}

MatrixForm /@ FoldList[#2 . #1 &, v, {cmat, bmat, amat}]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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