Dot notation / vectorized code syntax

Hi all,

I’m having trouble with dot notation. Can someone show me how to write the below code without expanding the square? I included a working example below, and then the code I would like to write that’s throwing an error.

This works:
‘’’
model(x)=exp.(x.^2)
model([1,1])
‘’’
however the following fails
model(x)=exp.((x.-2)^2)
model([1,1])

Thanks!

 model(x)=exp.((x.-2).^2)

or

model(x)= @. exp((x-2)^2)
2 Likes

Great, thanks for the quick reply! I need to take some time to review the dot notation properly.

The best way to write this is to write the function without the “dot” syntax. Then apply the dot when calling the function.

model(x)=exp((x-2)^2)
model.([1,1])

It’s also easier to reason about the function this way. You can easily test whether or not the function gives the expected output.

5 Likes

Another example: suppose you were studying the function f(x)=x^2. It is more useful to define f as

f(x)=x^2

than it is to define f as

f(x) = x.^2

With the first form you can evaluate f at a single value or over an array of values.

f(0)
# or 
f.([1, 2, 3])

You also can’t easily plot f if you use the second form.

1 Like

In this case I’m using the model in the LsqFit package, so I don’t have control over how it’s called. This way does look cleaner to me, so thanks for pointing out this alternative.