M. Kuehn
M. Kuehn

Reputation: 1

Summation notation for matrices in Matlab

I have a 4x4 matrix in Matlab named P. I want to raise P to a power (say, X) to create a new 4x4 matrix. Then, I want to sum that matrix from 0 to 51 (i.e. P^0 + P^1 + ... + P^52)

Of course, this would take far too long to write all the way out. Is there a way to shorten this?

I have already tried the following code:

 syms k

 symsum(P^k, k, [0 51])

which does not return what I want.

Thanks

Upvotes: 0

Views: 209

Answers (4)

Adiel
Adiel

Reputation: 3071

If there is a place, after some good ideas from @gnovice, my intuition was simply to vectorize it. That just another manner to what gnovice did, but in my opinion it's more readable than bsxfun.

result=reshape(sum(P(:).^[0:51],2),size(P))

Upvotes: 0

gnovice
gnovice

Reputation: 125874

A vectorized solution can be done with bsxfun like so:

result = sum(bsxfun(@power, P, reshape(0:51, [1 1 52])), 3);

For MATLAB versions R2016b and later, this can be done with implicit expansion (known as "broadcasting" in other languages):

result = sum(P.^reshape(0:51, [1 1 52]), 3);

If you really are trying to do it symbolically and not getting the result you want, it may be because you are using the wrong operator. The matrix power operator is ^, while the element-wise power operator is .^. You may be wanting this (where P is a 4-by-4 numeric matrix):

syms k
symsum(P.^k, k, [0 51])

Upvotes: 1

OmG
OmG

Reputation: 18838

You can do it like the following using subs (in octave):

syms 'P' 'k';
subs(symsum(P^k, k, [0 51]), [1 1;1 1])

For example P = [1 1; 1 1].

Upvotes: 0

Sardar Usama
Sardar Usama

Reputation: 19689

Since you were using symbolic math, I hope you'd be having no problem with a loop.

req_sum = zeros(size(P));
for k=0:51                   %loop for all the powers
    req_sum = req_sum + P^k; %adding the results of each iteration
end

Upvotes: 0

Related Questions