Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Matlab - Summation

  1. Oct 31, 2012 #1
    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. jcsd
  3. Oct 31, 2012 #2

    Simon Bridge

    User Avatar
    Science Advisor
    Homework Helper
    Gold Member
    2016 Award

    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.
     
  4. Nov 1, 2012 #3
    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.
     
  5. Nov 1, 2012 #4
    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)
     
  6. Nov 1, 2012 #5

    Simon Bridge

    User Avatar
    Science Advisor
    Homework Helper
    Gold Member
    2016 Award

    ... 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.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Matlab - Summation
  1. & vs. && for MATLAB (Replies: 2)

  2. Matlab concatenation (Replies: 2)

  3. Matlab and physics (Replies: 3)

  4. MATLAB problem (Replies: 1)

  5. MATLAB histogram (Replies: 3)

Loading...