How to match data from two separate variables, then extract it as a new variable?

I'm working with two variables where the first column is time as a decimal number, then a second column with my data shown as such:
Let's call these variables A and B. I need to match the decimal times from the first column of both variables, then extract the resulting times and the data attached to those times. So the result can either be:
  1. ResultingVariableA = [MatchedTimes;A_MatchedTimes] and ResultingVariableB = [MatchedTimes;B_MatchedTimes]
  2. ResultingVariable = [MatchedTimes;A_MatchedTimes;B_MatchedTimes]

4 Comments

The time data in column 1 of both the variables does not seem to be matching from the image that you have shared. I cannot see any common time values. Also there are a lot of repetitions in your time data. Do you also wish to eliminate the repeated entries?
The first variable is significantly longer (~24000 rows), whereas the second variable is only 5000 rows. The common times are a further down the first variable. I do not wish to eliminate the repeated times.
Can you attach the mat file?

Sign in to comment.

Answers (2)

You need to go for interpolation......you need to interpolate both the data to common time stamps. Have a look on interp1
One way of achieving this is by using the ismember function. You can read about it here:
https://www.mathworks.com/help/matlab/ref/ismember.html
I am attaching a simple program to illustrate how you may work with this:
A=[ 1,45;
2,56;
3,89;
3,89;
4,66;
5,23;
5,55]
B=[3,77;
3,88;
5,90;
5,100;
6,78] %note that there are repetitions in this data
[common,loc]=ismember(A(:,1),B(:,1)) %common: logical array(entry=1 wherever element of A is present in B.)
% Note that loc has the "smallest" index in B where this common value is present.
x=[];
for i=1:length(A)
if common(i)
if ismember(A(i,1),x) %if this is a repeated entry
loc(i)=loc(i)+count; %I had to do this since loc only stores the smallest index and there is repetition in your data.
count=count+1;
else
count=1;
end
x=[x;A(i,1),A(i,2),B(loc(i),2)]; %x is the final array you desire
end
end
You can try running this code and observe common and loc and you will easily be able to understand the workflow.

Categories

Products

Release

R2017b

Asked:

on 11 Jun 2018

Answered:

on 13 Jun 2018

Community Treasure Hunt

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

Start Hunting!