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

Debugging equations. vectorized vs. for-loop

  1. Aug 3, 2011 #1


    User Avatar
    Gold Member

    I get different results from these two functions. I need a fresh pair of eyes to help me find the discrepancy. The old way I did it, with the for-loop, gave proper results (but is slower, I think).

    VECTORIZED (wrong):

    Code (Text):

    Nss = .5*(1+tanh((y(1,:)-V3)/V4)); %N as t --> inf
    tau = 1./(phi*cosh((y(1,:)-V3)./(2*V4)));

    dy(:,2) = (Nss-y(2,:))./tau;

    a4 = (Nss(1)-y(2,1))./tau(1);

    save newodeset a4
    vectorized result:
    a4 = 0.5300

    FOR-LOOP (right):

    Code (Text):
     Nss = .5*(1+tanh((y(1)-V3)/V4)); %N as t --> inf
    tau = 1/(phi*cosh((y(1)-V3)/(2*V4)));
    dy(2) = (Nss-y(2))/tau;

    a4 = a4 = (Nss-y(2))/tau;
    for-loop result:
    a4 = 0.4572
  2. jcsd
  3. Aug 3, 2011 #2


    User Avatar
    Gold Member

    MATLAB, by the way.
  4. Aug 3, 2011 #3
    On first glance, why no ./ or .* in line 1 of the vectorized? Don't you get a dimension mismatch error?
  5. Aug 3, 2011 #4


    User Avatar
    Gold Member

    Matlab doesn't have a problem with the vector in the numerator, so onlly the 1./() was necessary. I added the . in the second line out of desperation. Upon your suggestion, I also tried adding the . in but I get the same result (it diverges to Inf/NaN)

    I also further dissected the (Nss-y(2,:))./tau term

    and found the problem to be in the "y(2,:)" which is the second variable in the ODE, so it's possibly not even anything to do with this code. All the other values in the expression remain the same in both codes... maybe I'm not catching the right time to compare, I don't know.

    This is just an excerpt of my whole code. I'd hoped I'd narrowed it down, but not sure anymore.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook