Question ) What is the difference between putting @. and . for every algebraic operator?

I am not sure if I am using the macro @. well. I thought I can avoid putting . (elementwise calculation) for + , -, / and so on by using the macro. For my project, I used it several times, but sometimes it doesn’t work. I would like to know what I am missing.

For instance, I have a function with a multi-dimensional array input :

**    for i in 1:length(x)**
**        if x[i] < 0 **
**            x[i] = 0**
**        end**
**    end**
**    return(x)**
**end**

and

**    z =  max_op(y) .+ max_op( (indi_bel .- b .+ β .* δ .* max_op(y)) ./ (1-β*k) .- max_op(y))**
**    return(z)**
**end**

When I run these two functions, it runs perfectly. However when I use @. macro,

**function intern_A(y)**
**    z =  @. max_op(y) + max_op( (indi_bel - b + β * δ * max_op(y)) / (1-β*k) - max_op(y))**
**    return(z)**
**end**

the following error occurs: “methodError: no method matching setindex!(::Float64, ::Int64, ::Int64)”.

Is it because the type of the output of max_op function is unsuitable for the macro?
Any responses would be more than appreciated.

Welcome! Please quote your code by surrounding it with triple backticks (```) to make it easier to read.

When you use z = @. max_op(y) + ..., max_op also receives a dot. It’s the same as if you had written

z = max_op.(y) .+ max_op.(...)

So in max_op, x[i] = 0 fails because you can’t index into a Float to set a value. After all, it’s already a scalar.

2 Likes

Now I completely understand !
Thank you very much !

You’re missing a dot, it’s the same as

z = max_op.(y) .+ max_op.(...)

and all other function calls inside max_op are dotted as well. @. is useful when you want to broadcast all the function calls in the expression you apply it to. A typical case where you don’t want to use @. is when you a matrix multiplication A * B: @. A * B would turn it into an element-wise product, if possible

1 Like

Whoops! Yes of course, my bad.

Yes, inside the brackets after max_op, but not inside the function max_op itself - important distinction!

1 Like

Since it’s marked as the solution, maybe you can edit the answer?

2 Likes

Done! Must have missed it before.