UndefVarError although I have defined it in the function before using it

Try du = @. ... instead of @. du = .... The reason is that @. x = y expands into x .= y, which means copy y to existing x.

3 Likes