0

I'm trying to write a script for the sum of the $j$-th powers of the first $n$ numbers in MATLAB, so:

$s(n,j) = 1+2^j+3^j+\cdots +n^j$

The function should have two inputs so I have started with:

% Sum of the j-th powers of the first n numbers

function z = sumofpowers(n,j)

y=zeros(1,n); y(1)=1;

for

Then I am stuck on how to actually write this function in MATLAB.

Can someone help?

EDIT:

This is my full code:

% Sum of the j-th powers of the first n numbers

function z = sumofpowers(n,j)

y=zeros(1,n);

y(1)=1;

for y=2:n
end

z = sum(y.^j)

Edward
  • 1

1 Answers1

0

Try this:

y = 1:n;
z = sum(y .^ j)

Note that .^ denotes element-by-element power raising. For example, [1 3 -2] .^ 2 evaluates to [1 9 4].

Adriano
  • 41,576
  • Hmmm, I am trying this: % Sum of the j-th powers of the first n numbers

    function z = sumofpowers(n,j)

    y=zeros(1,n); y(1)=1;

    for y=2:n
    end

    z = sum(y.^j)

    – Edward Nov 04 '13 at 12:11
  • sorry if that is hard to read, I will edit my first post. But this isn't working, say I do "sumofpowers(3,3)" it is just giving me the value of $3^3$ – Edward Nov 04 '13 at 12:12
  • @Edward I'm pretty sure Adriano's solution should work. What does sum([1:4].^2) give you? – in_mathematica_we_trust Nov 04 '13 at 12:17
  • That gives me the correct answer so I am presuming my script (see original post) is incorrect? – Edward Nov 04 '13 at 12:20
  • @Edward If you insist on using a for loop (which isn't very MATLAB like and is not recommended), then you should probably try something like: for k=1:n, y(k) = k; end; z = sum(y.^j) – Adriano Nov 04 '13 at 18:35