Defining matrices in MATLAB

239 Views Asked by At

I'm completely new to MATLAB, and I can't figure out how to do the following: I have

A=[-1,0.4,0.8;1,0,0;0,1,0];
b=[0;0.3;6];

What I want to do is define, for $N$ fixed but arbitrary, a $3\times N$ matrix C by having the $i$th column of C be $A^{(N-i)}b$. Without doing the calculations separately beforehand, how can I have MATLAB compute and set C as this matrix?

2

There are 2 best solutions below

9
On BEST ANSWER
A=[-1,0.4,0.8;1,0,0;0,1,0];
b=[0;0.3;6];
N=10;
Ai=eye(3); % Identity 3 x 3 matrix
C=zeros(3,N);
for i=1:N
    C(:,N-i+1)=Ai*b;
    Ai=Ai*A;
end

Note that the first column of C will be equal to $A^{N-1}b$, while the last column will be equal to $b$. If you wanted them to be $A^Nb$ and $Ab$ respectively then replace the fourth line of the code with

Ai=A;

Edit: The code in littleO's answer is much faster. Mine is an example of what you shouldn't do (at least when you care about efficiency)!

0
On

This code avoids having a matrix-matrix multiplication at each iteration.

A = [-1,0.4,0.8;1,0,0;0,1,0]; 
b = [0;0.3;6];
N = 5;

C = zeros(3,N);
vec = b;

for i = N:-1:1

    C(:,i) = vec;
    vec = A*vec;

end

Here's another option in Matlab:

C = fliplr(gallery('krylov',A,b,N));