Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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)


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

share|cite|improve this question
up vote 2 down vote accepted

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:



for k=1:n

x = x + A^k


share|cite|improve this answer
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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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