Basic use of sum command help

조회 수: 6 (최근 30일)
Daniel Millam
Daniel Millam 2015년 3월 30일
편집: John D'Errico 2015년 3월 30일
Recall that a geometric sum is a sum of the form a + ar + ar2 + ar3 + . . ..
(a) Write a function file that accepts the values of r, a and n as arguments and uses a for loop to return the sum of the first n terms of the geometric series. Test your function for a = 3, r = 1/2 and n = 10.
S = 0;
a=3;
r=1/2;
for n=0:1:10;
S=S+a*r^n;
end
S
This works, So I'm good here.
(b) Write a function file that accepts the values of r, a and n as arguments and uses the built in command sum to find the sum of the first n terms of the geometric series. Test your function for a = 3, r = 1/2 and n = 10. Hint: Start by defining the vector e=0:n-1 and then evaluate the vector R = r.^e. It should be easy to figure out how to find the sum from there
This is where I am stuck. Keep in mind that I have only been using MATLAB for about a week now. Any help is appreciated, I don't even know where I should start with this. Thank you.

채택된 답변

Image Analyst
Image Analyst 2015년 3월 30일
Declare the function
function theSum = yourFunctionName(r, a, n)
In the function get rid of the "for" loop - just have n=0:1:10;
Then use .^ instead of ^. Then a few more little things you can get rid of - hopefully you can figure those out.
That should be more than enough hints for you to complete it.
  댓글 수: 1
Daniel Millam
Daniel Millam 2015년 3월 30일
I did exactly what you said and ended up with
function [y] = f(r, a, n)
a=3;
r=1/2;
n=0:1:10
y=sum(a*r.^n)
end
AND IT WORKED Thank you very much.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

John D'Errico
John D'Errico 2015년 3월 30일
편집: John D'Errico 2015년 3월 30일
Ok, you did a decent job on the loop. Now it is time to learn how NOT to use a loop. :)
What if you create a vector n?
r = 0.5;
a = 3;
n = 10;
e = 0:1:(n-1);
Now, suppose you considered the vector:
a*r.^e
What would the elements of that vector represent?
What would result if you applied sum to that vector? Thus,
S = sum(a*r.^e);
Effectively, we have avoided the explicit for loop, working on vectors of elements instead.
  댓글 수: 1
Daniel Millam
Daniel Millam 2015년 3월 30일
Very helpful, Thank you.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by