Reputation: 27
I have been through a bunch of questions about the Repeat function in MatLab, but I can't figure out how this process work.
I am trying to translate it into R, but my problem is that I do not know how the function manipulates the data.
The code is part of a process to make a pairs trading strategy, where the code takes in a vector of FALSE/TRUE expressions.
The code is:
% initialize positions array
positions=NaN(length(tday), 2);
% long entries
positions(shorts, :)=repmat([-1 1], [length(find(shorts)) 1]);
where shorts is the vector of TRUE/FALSE expressions.
Hope you can help.
Upvotes: 0
Views: 1376
Reputation: 14336
The MATLAB repmat
function replicates and tiles the array. The syntax is
B = repmat(A,n)
where A
is the input array and n
specifies how to tile the array. If n
is a vector [n1,n2]
- as in your case - then A
is replicated n1
times in rows and n2
times in columns. E.g.
A = [ 1 2 ; 3 4]
B = repmat(A,[2,3])
B = | |
1 2 1 2 1 2
3 4 3 4 3 4 __
1 2 1 2 1 2
3 4 3 4 3 4
(the lines are only to illustrate how A
gets tiled)
In your case, repmat
replicates the vector [-1, 1]
for each non-zero element of shorts
. You thus set each row of positions
, whos corresponding entry in shorts
is not zero, to [-1,1]
. All other rows will stay NaN
.
For example if
shorts = [1; 0; 1; 1; 0];
then your code will create
positions =
-1 1
NaN NaN
-1 1
-1 1
NaN NaN
I hope this helps you to clarify the effect of repmat
. If not, feel free to ask.
Upvotes: 1
Reputation: 35525
repmat
repeats the matrix you give him [dim1 dim2 dim3,...]
times. What your code does is:
1.-length(find(shorts))
: gets the amount of "trues" in shorts
.
e.g:
shorts=[1 0 0 0 1 0]
length(find(shorts))
ans = 2
2.-repmat([-1 1], [length(find(shorts)) 1]);
repeats the [-1 1]
[length(find(shorts)) 1]
times.
continuation of e.g.:
repmat([-1 1], [length(find(shorts)) 1]);
ans=[-1 1
-1 1];
3.- positions(shorts, :)=
saves the given matrix in the given indexes. (NOTE!: only works if shorts
is of type logical
).
continuation of e.g.:
At this point, if you haven't omit anything, positions should be a 6x2
NaN
matrix. the indexing will fill the true
positions of shorts
with the [-1 1]
matrix. so after this, positions will be:
positions=[-1 1
NaN NaN
NaN NaN
NaN NaN
-1 1
NaN NaN]
Hope it helps
Upvotes: 3