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

4 views (last 30 days)
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

Sign in to comment.

Answers (2)

KSSV
KSSV on 12 Jun 2018
You need to go for interpolation......you need to interpolate both the data to common time stamps. Have a look on interp1

Kaninika Pant
Kaninika Pant on 13 Jun 2018
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

Find more on Numeric Types in Help Center and File Exchange

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!