Finding the approximate length with for loop?
Show older comments
(f,g,a,b,n) which takes five inputs: f: A function handle. g: A function handle. a: A real number. b: A real number. n: A positive integer. Note: You may assume that that a < b. Question: The functions f(t) and g(t) determine the location of an object at any time t by (f(t), g(t)). Approximate the distance traveled by the object between t = a and t = b by dividing [a, b] into n equal subintervals, determining the location of the object at each of those t-values and then by finding the straight-line distance between those locations and adding them.
Code:
function results = mylength(f,g,a,b,n);
totalLength = 0;
interval = sqrt((f-a)^2+(g-b)^2);
for x = [a:interval:b]
if x<b
totalLength = totalLength + x + interval;
end
end
results = totalLength;
end
Error: I am getting an error at the start of the for loop. I know I am getting that error because in interval I am using 4 variables and not just 2 variables. Also an error with how I am calculating interval. Can someone help/tell me how I would adjust the code to solve for this problem.
6 Comments
Stephen23
on 6 Mar 2015
I don't get any error:
>> mylength(1,2,3,4,0)
ans =
5.8284
Can you explain what you are doing that generates the error, and give us the exact and complete error message.
Jan
on 6 Mar 2015
Moved from Answer section:
Anyone help me?
[Please do nut bump a question by adding a non-answer in the answer section. Thanks]
Bob
on 8 Mar 2015
Edited: Geoff Hayes
on 8 Mar 2015
Geoff Hayes
on 8 Mar 2015
Bradley - the first input to your function mylength is a function handle which corresponds to the f input of your function. In the third line, your code is doing
interval = sqrt((f-a)^2+(g-b)^2);
where it tries to subtract a from the function f. what do you really mean to happen at this line? Please describe in detail why f and g are function handles and whether your mylength function requires this to be true.
Bob
on 8 Mar 2015
Bob
on 9 Mar 2015
Accepted Answer
More Answers (0)
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!