Debugging equations. vectorized vs. for-loop

  • Thread starter Thread starter Pythagorean
  • Start date Start date
  • Tags Tags
    Debugging
AI Thread Summary
The discussion revolves around discrepancies in results between vectorized and for-loop implementations of a MATLAB function. The vectorized version yields a result of a4 = 0.5300, while the for-loop produces a4 = 0.4572, with the for-loop being slower but accurate. A potential issue identified is the handling of the variable "y(2,:)", suggesting that the discrepancy may not stem from the vectorized code itself. The user also notes confusion regarding dimension mismatches and the necessity of using element-wise operations. Ultimately, the user is seeking assistance to pinpoint the source of the differing results in their equations.
Pythagorean
Science Advisor
Messages
4,416
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
MATLAB, by the way.
 
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.
 

Similar threads

Back
Top