Finalizing my Code for taylor series, gets error

1 view (last 30 days)
Japoe25
Japoe25 on 7 Apr 2015
Commented: Japoe25 on 7 Apr 2015
I'm trying to make a taylor series expression for e^x = sum(x^n/n!) for n=0:50 and for x^n/n!>0.01 So far I have this:
function [ xs ] = myExpfunction(x)
xs=zeros(1,length(x));
xl=zeros(51,1); %preallocation of the storage
for n= 1:50
if ((x.^n)/factorial(n))>0.01
xl(n+1,:) = ((x.^n)/factorial(n)); %save every iteration result
end
end
for ii = 1:length(x)
xs(ii)=1+sum(xl(:,ii)) ; %calculate the sum of the iteration results
end
end
I get and error:
??? Subscripted assignment dimension mismatch.
Error in ==> myExpfuntion at 6
xl(n+1,:) = ((x.^n)/factorial(n)); %save every iteration result
Im trying to get a result of for example x=[1,2,3,4] into xs=[2.7083 7.3810 20.0797 54.5940]. Thank you in advance for the help :)

Accepted Answer

Geoff Hayes
Geoff Hayes on 7 Apr 2015
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
xl=zeros(51,length(x));
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)); %save every iteration result
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.
  1 Comment
Japoe25
Japoe25 on 7 Apr 2015
wow this is everything I needed, Thank you so much!!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!