Gautam Sagar
Gautam Sagar

Reputation: 63

Summation in Matlab without for/while loop

How Do i solve this summation in MATLAB without using for/while loop? Here C is a vector(1*N matrix), n=length(c) and x is scalar. c(1)*x^1+c(2)*x^2+c()*x^3+....+c(n)*x^n.

Or can i Create a matrix with all element equal to x but with increasing power, like x, x^2,x^3....?

Upvotes: 1

Views: 264

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112769

There are several ways:

  • result = polyval(fliplr([0 c]), x);
  • result = sum(c.*x.^(1:numel(c)));
  • result = sum(c.*cumprod(repmat(x, 1, numel(c))));

As an example, for

c = [3 4 -5 2 3];
x = 9;

any of the above gives

result =
      186975

Check:

>> c(1)*x^1+c(2)*x^2+c(3)*x^3+c(4)*x^4+c(5)*x^5
ans =
      186975

Upvotes: 3

Related Questions