Adding an element during each iteration of the loop at the end of an existing array

조회 수: 12 (최근 30일)
MacLaurin equation
function result = MacLaurin(a,n)
% Program to calculate MacLaurin expression
% calculating factorial for the expression
fact = [1];
a = [1]
vec = [1:n];
% loop to calculate factorial and add the element to fact
for i = 2:n
c = prod(1:i);
% now i want to add c to array fact
fact[,c];
end
% here i want to put respective factorial values, how to write this part?
a = [a, 1./fact];
b = [1, a.^vec];
% adding respective elements to obtain final expression
result = 1 + b./a;
result = sum(result);
end

채택된 답변

Alberto Mora
Alberto Mora 2019년 1월 28일
편집: Alberto Mora 2019년 1월 29일
Try this:
function Res = MacLaurin(a,n)
% Program to calculate MacLaurin expression
% calculating factorial for the expression
Res=0;
% loop to calculate factorial and sum to the previous
for i = 0:n
Res = Res + a^i/factorial(i);
end
end
Regards
  댓글 수: 3
Alberto Mora
Alberto Mora 2019년 1월 29일
편집: Alberto Mora 2019년 1월 29일
I'm sorry but I do not understand your question.
In the following version, you create a long vector with each term in the for loop, and at the end you sum all the terms. Is it answer to your question?
function Res = MacLaurin(a,n)
% Program to calculate MacLaurin expression
% calculating factorial for the expression
Res=0;
% loop to calculate each factorial term in the Res array
for i = 0:n
Res(i+1) = a^i/factorial(i);
end
Res=sum(Res);
end
Rishabh Umrao
Rishabh Umrao 2019년 1월 29일
편집: Rishabh Umrao 2019년 1월 29일
Hi Alberto,
Yes, your method is correct and answer it is giving is also correct but,
I was trying to ask that if we can do by this method -->
function result = MacLaurin(a,n)
% Program to calculate MacLaurin expression
% calculating factorial for the expression
a = cumprod(1:5);
disp(a);
b = 1./a;
vec = 1:5;
d = 0.5.^vec;
c = 1 + sum(d.*b);
result = c;
end
I did some brain storming and found out one silly mistake that was creating some error.
By the way thanks for answering my doubt and showing me another method which can give the same result.
I was particular about this method because my assignement was to solve in this way, without using loops.

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by