Get time span between two outcomes of a random pick

I have two vectors, in one (a) there are the outcomes of a random pick (e.g. random letters from the alphabet) and in the other (b) the date of the pick (in numbers). For example:
a=[a;b;a;c;b;b;f;a] b=[42653; 42649; 42642; 42641; 42636; 42634; 42632; 42632]
I'm looking for a way to get a vector (c) in which I have the time span between the time of the pick and the time that outcome came out previously. In this case c should be:
c=[11; 15; 10; 0; 2; 0; 0; 0]

 Accepted Answer

Huh? An explanation that is clear as mud.
First, I'd suggest not writing something like this:
a=[a;b;a;c;b;b;f;a]
That is not meaningful code. Since apparently a,b,c, etc are letters, but then you treat a as a vector, then overwriting a.
Next, learn to use numbers instead of letters here. The numbers in a as coming from the set 1:7 will be far easier to work with. At some point, if you need to display them, then it is a simple table lookup, or even easier, just use char:
a = [1 2 1 3 2 2 6 1]';
char(a + 'a' - 1)
ans =
ans =
a
b
a
c
b
b
f
a
While I have no real certainty as to what you are asking, it seems like a simple search would work. Use find, in a loop.
c = zeros(size(a));
for letter = 1:7
ind = find(a == letter);
c(ind(1:end-1)) = -diff(b(ind(1:end)));
end
c
c =
11
13
10
0
2
0
0
0
Not the same as what you seem to expect, just one of the several reasons I said this was clear as mud. My guess is you cannot subtract. Or perhaps you did the computation wrong. Or perhaps you were just very unclear about what you intended.

2 Comments

I'm sorry for my bad explanation, I tried to simplify my problem to make it easier to understand but clearly I failed.
Actually my two vectors are much longer than those that I used here. I'm analyzing acquisitions of firms so I have data on the name of the acquirer and the date of the acquisition. In one vector there are all the names of acquirers and in the second all the dates of acquisition.
I want my code to look (for each acquirer) when the name of the same acquirer appeared previously and compute the time span between the two appearances.
Thank you for your help
But it matters not that your vectors are longer. The code I wrote will still work, and work fairly efficiently. So what is the problem? If you insist on storing the "names" in some unexplained string form, then you just need to use a tool that can search strings. For example, regexp, strfind, strmatch, ismember, losts of them.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!