How to save variables from multiple function iterations
Show older comments
I have this functions that computes the area under the curve of a function to a certain accuracy (tolerance):
function area = adaptQuad(f,a,b,tol)
% code that finds the first approximations over the intial interval [a,b]
% approx2 is always more accurate than approx1
% approx1;
% approx2;
% initial step size
h = (b-a)/2;
if abs(approx1 - approx2) < tol
% the new interval 'worked'
area = approx2;
else
% if the accuracy isn't met, the function calls itself, dividing the interval in half
area = adaptQuad(f,a,a+h,tol/2) + adaptQuad(f,a+h,b,tol/2);
end
end
The function first tests [a,b], then loops until it finds a small enough interval [a,x] that meets the tolerance, and then moves forward to test the remaining part of the interval [x,x+h].
If you output the intervals as the function runs, it would look something like
%intial interval [a,b] = [-1,1]
[-1,1] % not accurate enough, need smaller interval
[-1,0] % Accuracy met, now test the remaining interval
[0,1] % not accurate enough
[0,0.5] % not accurate enough
[0,0.25] % Accuracy met, now test the remaining interval
[0.25,0.5] % Accuracy met, now test the remaining interval
[0.5,1] % Accuracy met, end of initial interval
I want to save each interval where the accuracy was met into a ix2 matrix. Where i is the number of times the if statement is met.
if abs(approx1-approx2) < tol
area = approx2;
ints(i,1) = a;
ints(i,2) = b;
end
However, I don't know how to initialize this matrix, or keep the count of i. Any suggestions?
Answers (0)
Categories
Find more on Operating on Diagonal Matrices 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!