Help on loop function

I have a code written

‘’’
Y1 = (Data[1:15,10].* ((1 .- Data[1:15,4]) + (0.3 .* Data[1:15,4])))

‘’’

I now need the Y1 to go Y2, so on to Y10.

‘’’
Y2 = (Data[1:15,11].* ((1 .- Data[1:15,5]) + (0.3 .* Data[1:15,5])))

‘’’
As you can observe, some columns need to move increase by 1 (which I am hoping to code using the loop function)

I would like this to go on till Y10, with the columns changing (increase by 1)

Apologies, if this is difficult to understand.

Y = zeros(15,10)
for i = 1:10
    Y[:,i] =  (Data[1:15,9+i].* ((1 .- Data[1:15,3+i]) + (0.3 .* Data[1:15,3+i])))
end

Hint: Use triple backticks to typeset code. On my keyboard, you can find the backtick character in the top left corner right below esc, but your keyboard may be different.

Remember to dot the + and the assignment = too.

Also, can’t you simplify the expression like this?

Y[:,i] .=  Data[1:15,9+i] .* (1 .- 0.7.* Data[1:15,3+i])

For efficiency, you could also consider using views.

Do you really need to dot the = and the -? Dotting everything feels excessive.

You can add @. at the beginning of the expression and then you won’t need to do it more.

But you will learn to appreciate the dot syntax. It makes things clearer compared to matlab.

for i = 1:10
           Y[:,i] = @.  (Data[1:15,9+i] * ((1 - Data[1:15,3+i]) + (0.3 * Data[1:15,3+i])))
       end
1 Like

Yes, you do, or you can accept loss of performance and increased allocations. Alternatively, use @..

The point of dotting everything is that it all fuses into a single loop with no unnecessary intermediate arrays. If you drop it a single place, intermediate arrays are needed to hold each separate calculation, before combining them at the end.

4 Likes

What is the practical difference here between placing @. after = rather than at the beginning of the line?

Placing it after allocates a new array, and then stores the array.
Placing it before writes directly into Y[:,i].

Placing before is better.

4 Likes

The @. macro puts dots on all operators and function calls in the expression after the macro. It cannot put dots on things before the macro.

1 Like