MATLAB: Taking difference of adjecent elements by seting a custom order
diff command
Hi
I have the following vector:
[1 2 3 4 5 6]
I want to take the the difference between the third element and the first (3-1) and then fourth and second element (4-2) and so on. How do I do this?
Thank you!
Best Answer
Ali - you could create two vectors of indices that you can then use to perform the subtraction. One vector would be all indices starting from 3, 4, 5,... up to the last index (which would correspond to the length of the input vector), and the other vector would be all indices starting from 1, 2, 3,... up to two less than the end of the input vector. Try the following
A = [1 2 3 4 5 6];
idx2 = 3:length(A);
idx1 = 1:length(A)-2;
myDiff = A(idx2) - A(idx1);
Running the above returns
myDiff =
2 2 2 2
which correspond to the differences of 3-1, 4-2, 5-3, and 6-4.
while true %run until we get an acceptable sequence. break will quit the loop
test = (randperm(52) > 44) + 1; %create a random permutation of 44 1s and 8 2s
if min(diff(find(test == 2))) > 3 %minimum distance between 2s is 3
break;
end
end
Note: rather than creating a distribution that has an 85% probability of 1s and then checking that there are exactly 44 1s, I just directly create a random permutation of 44 1s out of 52. In my opinion, it makes more sense.
Best Answer