# Building a function to display of the sum of matrices at different powers in Matlab

I'm trying to write a for loop for the sum A+A^2+A^3+..+A^n.

Here is my code:

function [ x ] = Untitled2( A , n )

for k=1:n,

x =sum(A^k)

end

The problem I'm having with this is this function is listing the matrix A to each power without adding them. What can I do to add these together? Thank you in advance

-

Matlab's sum returns the sum along the first dimension not equal to one. If you want to add to x you would be best to use:

function[x]=Untitled(A,n)

x=zeros(size(A));

for k=1:n

x = x + A^k

end

-
This worked like a charm? An additional question: how would this work differently for a while loop? – Heath Huffman Nov 4 '13 at 22:18
It depends on what your while conditional is, I assume you want to iterate the same way until your have reached n sums: while k<n+1 x=x+A^k end – Jeremy Upsal Nov 4 '13 at 22:19
@Heath Huffman If this answer sufficiently answered your question, consider accepting it by clicking the check mark on the side, and up-voting the question. Your answerers will appreciate it! – dinkelk Nov 4 '13 at 22:42
First define k=0. – Jeremy Upsal Nov 4 '13 at 22:47
k should stop iterating when k=n+1, what are you inputting for n? I do not mind helping, but @dinkelk 's suggestion is true and appreciated. – Jeremy Upsal Nov 4 '13 at 22:52