I am trying for several days make this code faster. The function just takes a time series makes a Distance matrix of it and then compares components of it with Variance of that series and if component is smaller then Var, it substitutes it with 1 otherwise with 0.
I would like to use it on time series of length about 10000. F.e. Dat = N[Table[Sin[x], {x, 1, 10000}]];
My function is:
Rp[data_] := (
Clear[rr, N1, RR, DD];
rr = Variance[data];
N1 = Length[data];
RR = ConstantArray[0, {N1, N1}];
DD = DistanceMatrix[data] ^2;
For[i = 1, i < N1, i++,
For[j = 1, j < N1, j++,
If[DD[[i, j]] <= rr, RR[[i, j]] = 1; RR[[j, i]] = 1,
RR[[j, i]] = 0; RR[[i, j]] = 0]
]
];
RR
)
I have tried several options, substitute cycle with table and compile to c, but it didn't work better. This takes on my machine cca 10 min. I can run similar code on MATLAB like in 10 sec, where is the problem please, how to speed it up ?
Thank you guys for helping me, I didn't know I can use UnitStep
on whole Matrix.
But actually my whole problem is to calculate from the output Reccurence Rate-RR which is part of RQA analysis, my code is
Rqa[RP_] := (
Lmin = 2;
N1 = Length[RP];
Yout = Flatten[ConstantArray[0, {1, N1}]] ;
For[k = 2, k < N1, k++,
Onn = 1; While[ Onn <= N1 + 1 - k,
If[RP[[ Onn, Onn + k - 1]] == 1, A = 1; off = 0;
While[ off == 0 && Onn != N1 + 1 - k,
If[RP[[Onn + 1, k + Onn]] == 1,
A = A + 1; Onn = Onn + 1,
off = 1]
];
Yout[[A]] = Yout[[A]] + 1;
];
Onn = Onn + 1;
]
];
S = 2*Yout;
SR = 0;
For[i = 1, i < N1, i++,
SR = SR + i*S[[i]];];
RR = SR/(N1*(N1 - 1))
)
Which contains many loops and is also takes too much time, like 10 min for series of 10000 length = Input 10000*10000 matrix. From Michaels adviced topic I have read that I should replace For with Table ? I am afraid this wont help like in previous example. Can you please give me some advice or built in function which can help me ? I hope editing wont delete your comments.
RR = UnitStep[rr - DistanceMatrix[data]^2]
. $\endgroup$