How can I return a set of values in an array from a function file?
53 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(1 个)
Simon
2013-11-5
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!