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
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)
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:
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.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
.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]
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With