Append an array inside a function

I don’t really understand the scope of the variable SV here. I used it inside a function, so I expect that when I add elements to it, it should work fine:

SV = rand(10, 1)

function add_star(SV)

    for i =1:5

        append!(SV_new[:,1], 4)

    end

    return SV[:,1]
end

I am expecting the output of the function to be an array with 15 elements where the last 5 elements are 4, but the output is still an array with 10 elements, why?

SV[:,1] returns a new array. Instead you need to do @view(SV[:,1]), to get a view.

3 Likes

Sorry that was a mistake. The correct code is:

function add_star(SV)

    for i =1:5

        append!(SV[:,1], 4)

    end

    return SV[:,1]
end

Chances are, especially if you have a Matlab background, that you rather want a vector than a one-column matrix, in which case this is simply

SV = rand(10)
function add_star(SV)
    for i = 1:5
        append!(SV, 4)
    end
    return SV
end

If you really want a matrix you have to go through some hoops to achieve the same thing.

4 Likes

But this doesn’t work. The output of the function is still an array with 10 elements.

No it has appened 5 4s:

julia> SV = rand(10);

julia> function add_star(SV)
           for i = 1:5
               append!(SV, 4)
           end
           return SV
       end
add_star (generic function with 1 method)

julia> add_star(SV);

julia> SV
15-element Array{Float64,1}:
 0.7833650176317701
 0.5668846033320463
 0.4391438535780501
 0.1708544616711889
 0.5183882750256887
 0.039540666370839306
 0.9220275850039967
 0.2936365813778392
 0.6266212769148911
 0.7356570139131633
 4.0
 4.0
 4.0
 4.0
 4.0

Note though, for single element additions you should use push! instead of append!.

4 Likes

There are two issues:

Every time you slice, you create a copy, so each SV[:, 1] inside the loop creates a new copy, and the SV[:, 1] in the return statement also creates a copy, and they are all different. So you have

for i in 1:5
    create copy of array
    append 4 to this copy
    forget the copy, the original array has not been modifieed
end
make another copy of the original unmodified array and return it

The second issue is that you cannot append or push scalars to a matrix, only to vectors. rand(10, 1) is a 2-dimensional array/matrix. You need to work with vectors, so it should be SV = rand(10). If you are coming from Matlab, this is a very common point of confusion. Matlab users tend to use rand(N, 1), zeros(N, 1), ones(N, 1) all over the place. You’ll have to rid yourself of that habit :wink:

4 Likes