For loop with translation measurement flexibility

With broadcast the following code will work if x

, y

and z

a scalar, vector size n

, or any combination thereof.

b = zeros(n)
b .= x.*y.*z .+ x

      

However, I need a for loop. The following for loop only works when it x

is a size vector n

, y

is a scalar, and z

is a scalar.

for i = 1:n
    b[i] = x[i]*y*z + x[i]
end

      

To write the equivalent b .= x.*y.*z .+ x

as a for-loop for any case, I can only think of writing a for loop for each combination x

, y

and z

inside if statements.It can get messy with a lot of variables in more complex math expressions.

Is there a more elegant way to do what I need than using many if statements?

+3


source to share


1 answer


You can define the type of wrapper that indexes into it will give array indexing if the wrapper variable is an array and repeats the same value for all indexes for scalars. I have an example below, but it's probably not as efficient as using it broadcast

. And it doesn't check if the array lengths are consistent. However, a custom wrapper type will make things easier.



julia> function f(x,y,z)
           lx,ly,lz = length(x),length(y),length(z)
           maxlen = max(lx,ly,lz)
           cx = cycle(x)
           cy = cycle(y)
           cz = cycle(z)
           b = zeros(maxlen)
           @inbounds for (xi,yi,zi,i) in zip(cx,cy,cz,1:maxlen)
               b[i] = xi*yi*zi+xi
           end
           return b
       end
f (generic function with 1 method)

julia> f(1:3,21,2)
3-element Array{Float64,1}:
  43.0
  86.0
 129.0

      

+5


source







All Articles