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?
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