# If-else loop failure for a large array

I have the following code:

``````    if sol[5,i] - sol_1[5,i] >= 0.0
s[i] = sol[5,i] - sol_1[5,i]
else
s[i] = sol_1[5,i] - sol[5,i]
end
end
``````

Now, here, sol and sol_1 correspond to 2 solutions I have from DifferentialEquations.jl (basically, I would like to plot the absolute value of the difference at each timestep; my solution vectors are same sized and have 6 variables - here, I am only considering the 5th variable).

Now, problem with this is that the code doesn’t work. I get both positive and negative values for s which certainly not what I intended. In fact, I ran the following line,

``````s = sol[5,i] - sol_1[5,i]
``````

This and the above code give me the same s. Any help would be appreciated!

1 Like
``````s = abs(sol[5,i]  - sol_1[5,i])
``````

You haven’t provided enough information for anyone to tell why your original code doesn’t work (suggested in the link in the other response). Maybe there’s something else in your loop overwriting `s[i]`. Sometimes unexpected branching can be due to comparing with NaN, but if that were the case you’d likely be complaining about `s` getting filled with NaN.

1 Like

Can you explain why you are using `if`/`else` instead of `abs`? It seems like a very particular, but odd, choice.

2 Likes

Ah, sorry. My code is quite large, so I skipped it (it takes time to run, and contains a lot of irrelevant portions). However, I did manage to figure it out (i.e. I managed to compute what I wanted), so there’s that.

Actually, I did at first. Must’ve made a typo there because it kept showing me error, so I went a more naive way. Anyhow, using abs.() works fine now, so I have just skipped the loop. Thanks a lot.