Script for the sum of the $j$-th powers of the first $n$ numbers in MATLAB

136 Views Asked by At

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)

1

There are 1 best solutions below

5
On

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].