Hi Rajn
First of all, I think you might have a typo in your range. Alternatively,
you computer is quite a bit faster than mine. If I set Z = 1:0.1:100
instead, the timings match yours.
Your solution for constructing z1 must win the prize for most inefficient
solution possible :-). Also, please note the difference between vectors and
matrices in Julia.
I also get that Matlab's repmat is a bit faster. However, in Julia you
should generally try to program in way that avoids repmat because repmat
often allocates much more memory than actually needed. In addition, it is
very expensive to expand the vector (matrix) during a loop the way you do
it. The @time macro will show you how much
julia> let
Z2=1:0.1:100
z2=Array(Float64,0)
@time for j=1:length(Z2)
z2=[z2, repmat([Z2[j]],length(Z2))]
end
end
elapsed time: 9.813421057 seconds (3904956256 bytes allocated, 47.48% gc
time)
i.e. almost four gigabytes are allocated along the way. You could get the
same result with the comprehension
julia> @time [[fill(x, length(Z)) for x in 1:0.1:100]...];
elapsed time: 0.016251751 seconds (15849088 bytes allocated)
i.e. slightly less than 16 megabytes and there are probably even better
solutions.
It appears, that Matlab's repmat runs in parallel, which our doesn't.
Hence, a way to get closer to Matlab speed would be to write a parallel
implementation of repmat, but as you see, it is better just to use a
different solution, so I doubt that much effort will be put into making our
repmat faster.
Med venlig hilsen
Andreas Noack
2014-10-13 18:05 GMT-04:00 Rajn <[email protected]>:
>
>
>
> Hi,
> I have two questions.
>
> First question:
>
> I have a fairly simple problem which can be solved in many ways.
>
> To begin I have a vector
> z1=Array(Float64,1,0)
>
> I have
> Z=1:0.01:100
>
> I would like to generate a vector in which each element is repeated
length(Z) times i.e., [1 1 1 1....length(Z) times 1.01 1.01
1.01....length(Z) times and so on
>
> When I do
> for j=1:length(Z)
> z1=[z1 repmat([Z[j]],1,length(Z)]
> end
>
> and compare the time for this exact code with Matlab's/Octave, Julia
takes 7 seconds in comparison to 1.5 seconds for Matlab/Octave.
>
> Of course I did not see any improvement using
> z1=[z1 ones(1,length(Z))*Z[j]]
>
> It took practically the same time.
>
> However, this reduced to fraction of a second...i.e., after I generated a
vector of zeros and just replaced the zeros appropriately.
> z1=zeros(1,length(Z)^2)
> length(Z)=dd
> for j=1:dd
> v=1:dd:(dd-1)*dd
> z1[1,v[j]:(v[j+dd-1])]=Z[j];
> end
>
> Of course even Octave/Matlab became equally fast with this code.
>
> So what gives in repmat for Julia? Why is it slow? Have I gone wrong with
my first code?
>
>
>
>
> Question 2:
> If I start with A=[]
> How do I vcat or hcat a row or a column vector to A in a for loop form a
MATRIX.
> say my vector is A(10x1) and I want to make B=[A[1] A[2] A[3] A[4]] which
is a 10x4 matrix.
> In Octave I would do
> B=[]
> B=[B A[j]] in a for loop.
>
> Thanks