How can I return a set of values in an array from a function file?

72 views (last 30 days)
I have a function file that I wrote and I want it to return 2 arrays of values not just a single value. My function file looks like this
function [yf,relError,count] = myroot(a,yb,error,countmax)
count=0;
while 1
ybold = yb;
yb= 0.5*(yb + a/yb);
count = count +1;
if yb ~= 0
relError = abs((yb-ybold)/yb);
end
if relError <= error || count >= countmax
break
end
end
yf=yb;
How can I create a vector or array that returns all calculated values of yf and relError? I think it would require me to initialize a vector made of zeros to begin with but Im not sure. Any help would be appreciated. Thank you.

Answers (1)

Simon
Simon on 5 Nov 2013
Hi!
First you may create an empty array like
yf = zeros(countmax, 1);
This gives you an array of maximum size. In your loop you set
yb= 0.5*(yb + a/yb);
count = count +1;
% now save in array
yf(count) = yb;
The same you do with your error.
You do not fill your vector up to the last entry with vales, depending on the error. So it is usefull to crop the vectors before returning from the function to get rid of the extra zeros, like
yf = yf(1:count);
And the same for the error.

Categories

Find more on Multidimensional Arrays 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!