What does this statement mean "Use a for loop to move x = 'a' half the distance to 'b' and do it 'n' times."

1 view (last 30 days)
I am creating a function m file called mystepcloser, this is the information I was provided with.
mystepcloser(a,b,n) which takes three inputs:
a: A real number.
b: A real number which you may assume is greater than 'a'.
n: A positive integer.
Does: Uses a for loop to move x = 'a' half the distance to 'b' and do it 'n' times.
Returns: The final value of 'a'.
I do not understand what it is suppose to do. What does it mean to move x='a' half the distance to 'b' and do it 'n' times. How would I go about creating a for loop that does this, and how would I make the for loop return the final value of 'a'?

Accepted Answer

Image Analyst
Image Analyst on 14 Sep 2014
Use a for loop
for k = 1 : n
In the for loop have a value called aNew that will get updated with the latest value of a. aNew starts at b. At each iteration calculate the difference between a and aNew - this is the distance. Divide the distance by 2 and add it to "a" to get a new aNew. This will go on "n" times and when you're done set a=aNew because you're supposed to have the final value in a. Actually the function should return the value
function aNew = mystepcloser(a,b,n)
If you do that you don't need to stuff aNew into a since the final value, aNew, is being returned. Good luck finishing the code. It's actually very easy.

More Answers (1)

David Young
David Young on 14 Sep 2014
Suppose a is 3 and b is 7. Then the 'distance' from a to b is 4, half the distance is 2, and moving a that much towards b means adding 2 to a to make it 5. Then do it again and a becomes 6 ... and so on.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!