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

68 vues (au cours des 30 derniers jours)
John
John le 5 Nov 2013
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.

Réponses (1)

Simon
Simon le 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.

Catégories

En savoir plus sur Multidimensional Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by