MATLAB: How to obtain array output from nested loops in user defined function

for loopfunctionwhile loop

Hi, I am trying to make a user defined function that will find e^x using the Taylor series. What I have is a While loop nested in a For loop in the function (see code). The function works great for single inputs of 'x', giving a single correct y value. However, when I try to enter a row vector for x, it only gives the final answer of the final term in the vector. When I make it show every value S (the final e^x value) it will show each output for each input, but as a separate answer and is useless because I will need them outputted together as a single matrix. Thanks for any help!
function [ y ] = mae_exp(x, E )
%x is the power you want to take 'e' to, E is the error you wish to have
f=1:1:length(x);
for X=x(1,f)
D = 100; n = 0; A=1; S=A;
while D>E
n = n+1; %stepping to next term
A = X.^(n)./factorial(n); %finding answer of n term
D = abs((S-(S-A))./(S-A)); %calculating error
S = A + S; %adding the all current terms together
end
y=S
end
end

Best Answer

Slight changes to your code:
function [ y ] = mae_exp(x, E )
%x is the power you want to take 'e' to, E is the error you wish to have
y = zeros(size(x)); % <-- pre-allocate result
for f=1:1:length(x); % <-- moved for loop to here
X=x(f); % <-- pick off f'th element of x
D = 100; n = 0; A=1; S=A;
while D>E
n = n+1; %stepping to next term
A = X.^(n)./factorial(n); %finding answer of n term
D = abs((S-(S-A))./(S-A)); %calculating error
S = A + S; %adding the all current terms together
end
y(f)=S; % <-- added subscript to y
end