Debugging equations. vectorized vs. for-loop

  • Thread starter Thread starter Pythagorean
  • Start date Start date
  • Tags Tags
    Debugging
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 2K views
Messages
4,430
Reaction score
327
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:
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:
 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
 
Physics news on Phys.org
On first glance, why no ./ or .* in line 1 of the vectorized? Don't you get a dimension mismatch error?
 
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.