MATLAB: Function data into columns

functions

Hello. I have created a function that inputs a vector of x-values, and outputs the value of the Taylor Polynomial of e^x for said x-values. My objective is to take this data, and output it into a single column using a single fprintf statement, but I have no clue how to do this due to my unfamiliarity with functions. Everytime I tried to output "TaylorExp(x)", I kept getting the output in rows. Note, there is a "Texp" output variable that I had to use within my assignment, but I also did not know where to incorporate it. Here is my code and any assistance would be appreciated.
function [Texp ] = TaylorExp(x) % function definition line
% H1: Computes e^x using a Taylor Series for x>=0
% Help Text:
% x = a vector of exponents, all values x >= 0
% Output Argument:
% Texp = a vector of e^x values computed using a Taylor Series
n=0; % sets iterations
x=[0:0.5:20];
while n<1
n=n+1;
if isinteger(x)
((x)^(n)/factorial(n))
else
exp(x)
end
end

Best Answer

When you do
if isinteger(x)
((x)^(n)/factorial(n))
else
exp(x)
end
then you compute either ((x)^(n)/factorial(n)) or exp(x) . Because there is no semi-colon after the computation, the default action is taken with the result, and that default action is to display the value. But you are not storing the value -- which is something you need to do because you need to return computed values.
Other notes:
  • you cannot use a vector of values "^" something. You need to use the vector ".^" the somethng. Not x^n but x.^n . This is because in MATLAB, the "^" operator is matrix exponentiation not element-by-element exponentiation.
  • Your "while" condition is only going to be executed once. You start with n = 0, and use "while n<1" so it will be true the first time. Then you have n = n + 1 so the 0 will become 1, which is not <1 so the while will not be true the second time. It seems more likely to me that you want to use a "for" loop running up to the maximum order you have defined to expand to (order 6 is pretty common)
  • isinteger() does not test whether its input has integral value: it test whether the input is one of the integer data types, such as uint8 or int32
  • you are testing the entire vector x at one time, not individual entries in x
  • but why are you testing if x is integral anyhow?
Related Question