# Matlab - Summation

1. Oct 31, 2012

### eurekameh

How can I do the summation of x^2 from 0 to 3 without the use of any built-in functions? I know a for loop is involved, but I can't get it to work.

Last edited by a moderator: Oct 31, 2012
2. Oct 31, 2012

### Simon Bridge

Sounds like an assignment ... the idea is for you to figure it out for yourself.
However: doesn't mean we cannot give you a nudge in the right direction ;)

Show us your best attempt and what happens when you run it.

3. Nov 1, 2012

### eurekameh

Lol, it's not an assignment per se, but I still need this piece of code.
I tried:

i = 0:1:3
x = i.^2
end

but this just uses each i = 1, i = 2, i = 3 to compute x = i^2. I'm looking for a way to somehow store each xi and add them to form the total summation.

4. Nov 1, 2012

### NemoReally

I'm not a Matlab user, but does x already store each i^2? There are a couple of ways you could do this: using a loop or a vectorized approach.

With a loop, look up 'for' and 'while' - essentially, you initialize the variable that you want to store the sum, then within a loop calculate each power and add it to the sum variable.

Alternatively, create a vector of '1's the same length as x and multiply them together vectorwise. ... the built-in function 'ones' is the obvious route to go but as you don't want to use built-in functions, do something like
o = x*0+1 (multiply x by 0 to create a zero vector of same size as x, then add 1)
s = x*o (scalar product of o and x)

5. Nov 1, 2012

### Simon Bridge

... and then there is always looking up the sum.m file that houses the built-in function that matlab uses ;)

Note: the sum of the squares of the elements of a vector is just the dot product with itself right? So - set up a vector of sequential numbers and dot product it with itself:

x=1:9;
s=x*x';

and s is the sum you want.

Matlab really rewards vector-based thinking.