Let’s say I have a function that can compute one output from one input, e.g.
function y = sqrt_newton(x)
y = x ./ 2;
yo = y;
y = 0.5.*(y + x ./ y);
while abs(y - yo) > eps * abs(y)
yo = y;
y = 0.5.*(y + x ./ y);
end
end
I’d like to be able to apply this function to a vector input say sqrt_newton(2:9) like with built-in functions. What is the best way to achieve this with a condition at the beginning of the loop or some if-clause inside? I’d like to avoid writing an extra function as a wrapper just to loop through the input vector, if possible at all.
My current cumbersome solution
What I do up until now is:
-
I have to expand first the inputs to the same size (using finargsz from the finance toolbox, but if you know of another core function that does the same, that would be great)
-
record the shape using
size -
dealthe inputs -
loop thru all the input elements
-
reshapethe output
It seems that the numel function alleviates the need of all this heavy lifting but extra comments would be most welcome.
There’s always
arrayfun. You can keep the code you have, putting it into an inner function.Edit: The above solution has the advantage of being trivial to implement after you have it working with a 1×1 input, but the loops in the other answers are way faster for large inputs. For example, on my computer, the code
runs in
~1.24 secondswith my code,0.06 secondswith @Ramashalanka’s code, and0.28 secondswith @GuntherStruyf’s code.