Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate values in Julia with Function

I need writing a function which takes as input

a = [12,39,48,36]

and produces as output

b=[4,4,4,13,13,13,16,16,16,12,12,12]

where the idea is to repeat one element three times or two times (this should be variable) and divided by 2 or 3.

I tried doing this:

c=[12,39,48,36]
a=size(c)
for i in a 
    repeat(c[i]/3,3)
end
like image 446
Misael Igor Alvarado Guimaray Avatar asked Dec 23 '22 19:12

Misael Igor Alvarado Guimaray


2 Answers

You need to vectorize the division operator with a dot .. Additionally I understand that you want results to be Int - you can vectorizing casting to Int too:

repeat(Int.(a./3), inner=3)
like image 152
Przemyslaw Szufel Avatar answered Dec 31 '22 09:12

Przemyslaw Szufel


Przemyslaw's answer, repeat(Int.(a./3), inner=3), is excellent and is how you should write your code for conciseness and clarity. Let me in this answer analyze your attempted solution and offer a revised solution which preserves your intent. (I find that this is often useful for educational purposes).

Your code is:

c = [12,39,48,36]
a = size(c)
for i in a 
    repeat(c[i]/3, 3)
end

The immediate fix is:

c = [12,39,48,36]
output = Int[]
for x in c
    append!(output, fill(x/3, 3))
end

Here are the changes I made:

  • You need an array to actually store the output. The repeat function, which you use in your loop, would produce a result, but this result would be thrown away! Instead, we define an initially empty output = Int[] and then append! each repeated block.
  • Your for loop specification is iterating over a size tuple (4,), which generates just a single number 4. (Probably, you misunderstand the purpose of the size function: it is primarily useful for multidimensional arrays.) To fix it, you could do a = 1:length(c) instead of a = size(c). But you don't actually need the index i, you only require the elements x of c directly, so we can simplify the loop to just for x in c.
  • Finally, repeat is designed for arrays. It does not work for a single scalar (this is probably the error you are seeing); you can use the more appropriate fill(scalar, n) to get [scalar, ..., scalar].
like image 30
Fengyang Wang Avatar answered Dec 31 '22 10:12

Fengyang Wang