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

MATLAB Double Sum Using Matlab

  1. Feb 21, 2012 #1
    I have this double summation expression to solve as part of matlab code I am writing. I have searched matlab no syntax that can do it. Please assist.

    Q=ƩƩxixjaij i.e double sum of xi xj aij, i=1:n, j=1:n

    Please assist me

  2. jcsd
  3. Feb 22, 2012 #2


    User Avatar
    Science Advisor

    What do mean by solve? What you have written is simply an expression. To solve something you need to describe what is known and what you are trying to find.
  4. Feb 22, 2012 #3
    Thanks Mathman,

    What I mean is this. I wrote a matlab code for that expression and manual as seen below but got different answer. I don't know what is wrong either with matlab code or manual expression or both.

    Q=∑∑xixjaij the first sigma has i=1:n, the second sigma j=1:n

    for i=1:n
    for j=1:n
    Q=sum(sum(x(i).*x(j).*(a(i, j))));



  5. Feb 23, 2012 #4


    User Avatar
    Science Advisor

    From what I recall about coding: You need to set Q = 0.0 before starting. Then the operating instruction should be Q=Q+x(i)*x(j)*a(i, j). To save a little time you could multiply by x(i) outside the j loop.
  6. Feb 24, 2012 #5
    if a is nxn and x is nx1 try Q = sum(sum(a.*repmat(x,[1 n]).*repmat(x',[n 1])))
  7. Feb 24, 2012 #6


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    This line is what is wrong with your code. Let's consider what happens on each loop:
    i=1, j=1:
    sum(sum(x(1)*x(1)*a(1,1))) = x(1)*x(1)*a(1,1) so Q=x(1)*x(1)*a(1,1)

    sum(sum(x(1)*x(2)*a(1,2))) = x(1)*x(2)*a(1,2) so Q=x(1)*x(2)*a(1,2) NOT x(1)*x(1)*a(1,1)+x(1)*x(2)*a(1,2)

    If you replace the line with
    you should get the right answer
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook