How can I make my function accept vectors instead of scalars(I'm Really New to Matlab)

조회 수: 1 (최근 30일)
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 ] = myExpfuntion(x)
x=input('Enter 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
xs=1+sum(xl) ; %calculate the sum of the iteration results
end
I want to delete the line "x=input('Enter x: ');" and just place my value for x in the function i.e. myExpfunction(x) and also make the function work with x being a row vector i.e x=[1 2 3]
My current function wont allow me to do so and I don't get what I'm doing wrong. Please help!

채택된 답변

Julia
Julia 2015년 4월 7일
Hi,
I modified you code so that vectors can be used as input.
However, I am not sure, if I did it in the right way. It should help you though to get what you want:
function [ xs ] = myExpfuntion(x)
xs=zeros(1,length(x));
xl=zeros(51,length(x)); %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 i = 1:length(x)
xs(i)=1+sum(xl(:,i)) ; %calculate the sum of the iteration results
end
end
This code results in:
>> xs=myExpfuntion([1,2,3,4])
xs =
2.7083 7.0000 16.3750 34.3333
  댓글 수: 3
Japoe25
Japoe25 2015년 4월 7일
Hello again Julia,
If it helps, I've had a look at the iteration results and saw that the iterations stop when they reach the length of x instead of at >0.01
xl =
0 0 0 0
1.0000 2.0000 3.0000 4.0000
0.5000 2.0000 4.5000 8.0000
0.1667 1.3333 4.5000 10.6667
0.0417 0.6667 3.3750 10.6667
Julia
Julia 2015년 4월 7일
Hello Japoe,
1/(5!) is smaller than 0.01. So for n greater than 4 the if statement is never true again. Perhaps you have to modify the if condition.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by