Home > Software design >  Replace values with for loop
Replace values with for loop

Time:09-18

Suppose I have the following function:

function y1(x)
    y = x^(2) - 4
    return y
end

Now, I want to evaluate all the values from this sequence: collect(range(-10,10, 1000))

I tried this

y_1 = zeros(1000);
for x in collect(range(-10, 10, 1000))
   y_1 = y1.(x)
end

Note that I use the broadcast operator to apply the function y1 for every value that takes the iterator. But if I don't use it I get the same result.

But as an answer, I just get 96.0.

How can I refill the y_1 vector with the for loop, so I get the evaluated values?

The evaluated vector should be of size 1000

Thanks in advance!

Edit:

I found a way to get to my desired result without the for loop:

y_1 = y1.(collect(range(-10, 10, 1000)))

But I still want to know how can I do it in a loop.

CodePudding user response:

The broadcast operator broadcasts the function over the entire iterator by itself i.e. y1.(arr) will

  • call y1 on each of the elements of the array arr
  • collect the results of all those calls, and
  • allocate memory to store those results as an array too

So the following are all equivalent in terms of functionality:

julia> arr = range(-4, 5, length = 10) #define a simple range
-4.0:1.0:5.0

julia> y1.(arr)
10-element Vector{Float64}:
 12.0
  5.0
  0.0
 -3.0
 -4.0
 -3.0
  0.0
  5.0
 12.0
 21.0

julia> [y1(x) for x in arr]
10-element Vector{Float64}:
(same values as above)

julia> map(y1, arr)
10-element Vector{Float64}:
(same values as above)

julia> y_1 = zeros(10);

julia> for (i, x) in pairs(arr)
          y_1[i] = y1(x)
       end

julia> y_1
10-element Vector{Float64}:
(same values as above)

In practice, there maybe other considerations, including performance, that decides between these and other choices.


As an aside, note that very often you don't want to collect a range in Julia i.e. don't think of collect as somehow equivalent to c() in R. For many operations, the ranges can be directly used, including for iteration in for loops. collect should only be necessary in the rare cases where an actual Vector is necessary, for eg. a value in the middle of the array needs to be changed for some reason. As a general rule, use the range results as they are, until and unless you get an error that requires you to change it.

  • Related