How to get incremental power matrix in matlab

I wanted to calculate the following matrix in Matlab:

    g=[I
       A 
       .
       .
       .
      A^N]      

I used the following program in Matlab:

A=[2 3;4 1];
s=A;
for n=1:1:50
   s(n)=A.^n;
end
g=[eye(1,1),s];

I get the following error:

In an assignment, the A(I) = Bnumber of elements in Band Imust be the same.
    Error in s_x_calcu_v1(line 5)
    s(n)=A.^n;

+1
source share
3 answers

The problem is that you are trying to assign a matrix to one element. In matlab, the caller s(n)means that you get the nth element s, regardless of the size of s. You can use a three-dimensional matrix

N = 50;
A=[2 3;4 1];

[nx,ny] = size(A);
s(nx,ny,N) = 0; %makes s a nx x ny x N matrix
for n=1:1:N
    s(:,:,n)=A.^n; %Colon to select all elements of that dimension
end
g=cat(3, eye(size(A)) ,s); %Add the I matrix of same size as A

Or a vectorized version

s = bsxfun(@power, A(:), 1:N);
s = reshape(s,2,2,N);
g = cat(3, eye(size(A)) ,s);

And the third solution using cumprod

s = repmat(A(:), [1 N]);
s = cumprod(s,2);
s = reshape(s,2,2,N);
g = cat(3, eye(size(A)) ,s);
+5
source

s 2 2, , .

s :

% --- Definitions
A = [2 3;4 1];
N = 50;

% --- Preparation
s = cell(N,1);

% --- Computation
for n=1:N
    s{n} = A.^n;
end

,

+3

When you cycle from 1to N, computing every time A.^n, you do LOTS of redundant calculations! note that

A.^n = (A.^(n-1)).*A; %//element-wise power
A^n = (A^n) * A; %// matrix power

In this way,

A = [2 3;4 1];
N = 50;
s = cell(N+1,1);
s{1} = eye(size(A,1));
for ii=1:N
    s{ii+1} = s{ii}.*A; %// no powers, just product!
end
g = vertcat( s{:} );

BTW, the same, if you want to calculate the matrix power (instead of elementary powers), all you need is changed tos{ii+1} = s{ii}*A;

+2
source

All Articles