Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

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:


function[x]=Untitled(A,n)

x=zeros(size(A));

for k=1:n

x = x + A^k

end

share|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
1  
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
1  
@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
1  
First define k=0. –  Jeremy Upsal Nov 4 '13 at 22:47
1  
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

 
discard

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.