Japoe25 - the error message is telling you that the assignment at
xl(n+1,:) = ((x.^n)/factorial(n));
is failing due to trying to assign too many elements to x1. Note that x1 is a 51x1 matrix whereas x is a 1x4 - so you are trying to squeeze four elements into one. You need to resize x1 as
The above will allow you to continue and get an answer that is almost correct. Note the condition for the if statement
if ((x.^n)/factorial(n))>0.01
Remember that x is a 1x4 array and so this condition will be false when at least one element of the four element ((x.^n)/factorial(n)) is less than 0.01. You want to continue updating xl so long as at least one element of this matrix satisfies the condition. You can do this with the any function as if any(((x.^n)/factorial(n))>0.01)
Adding this will give you results that are similar to what you are looking for. When I tried this, I found the answer to be
2.7183 7.3891 20.085 54.594
which is almost what you are looking for. You get the correct answers if you pass in each element individually as
myExpFunction(1)
myExpFunction(2)
myExpFunction(3)
myExpFunction(4)
The difference is due to the any - as long as one element in x produces a result that is greater than 0.01 then we continue computing the expansion for all values in x. To get around this you could do
for n= 1:50
temp = ((x.^n)/factorial(n));
temp(temp <0.01) = 0;
xl(n+1,:) = temp;
end
In the above, we create a temporary array and then set all of its values that are less than 0.01 to zero before the assignment to xl. This will give you the answer that you are looking for.
Best Answer