Summation x^2 0-3 w/o Built-in Matlab Fns: For Loop

  • Topic: MATLAB 
  • Thread starter Thread starter eurekameh
  • Start date Start date
  • Tags Tags
    Matlab Summation
Join the discussion
Registration is free. Start your own thread to ask a follow-up.
4 replies · 3K views
eurekameh
Messages
209
Reaction score
0
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:
Physics news on Phys.org
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.
 
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.
 
eurekameh said:
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.
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)
 
... 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.