Hi i'm new to MATLAB and i was wondering what this function actually does. The function was copied from a previous question that helped me out with a problem to find the frequency of a number in a row.
Link:
Series of consecutive numbers (different lengths)
d=[3 2 4 2 2 2 3 5 1 1 2 1 2 2 2 2 2 9 2]
q = diff([0 d 0] == 2);
v = find(q == -1) - find(q == 1);
Lets get to it step by step.
You have an array d
:
d=[3 2 4 2 2 2 3 5 1 1 2 1 2 2 2 2 2 9 2]
and you apply to it
q = diff([0 d 0] == 2);
This takes the derivative of [0 d 0] == 2
. Basically it takes the derivative of all the numbers that are 2. The result of [0 d 0] == 2
is:
0 0 1 0 1 1 1 0 0 0 0 1 0 1 1 1 1 1 0 1 0
You can see that there are 1 whenever there was a 2 in the original vector, and it has a 0 in the begging and a 0 in the end. If we take the derivative of this by q = diff([0 d 0] == 2)
:
q =
0 1 -1 1 0 0 -1 0 0 0 1 -1 1 0 0 0 0 -1 1 -1
You get 1 whenever a 2 in the original vector appeared and a -1 when in disappeared. The last line finds just the 1 and just the -1 separately and substract the indices where they appeared, that way you can now how many numbers are between them. As 1 means "number 2 starts" and -1 means "no more number 2s in a row" this will give you the length of the series of 2s in a row.
v = find(q == -1) - find(q == 1);
v=
1 3 1 5 1
There is a single 2 in the begining, then there is a series of 3 2s, then another single one, then 5 come and separated by a 9, the last one comes.