# How to subtract vectors with different number of entries?

2 views (last 30 days)
Sandy on 28 Feb 2013
I have two data files with two lines of data each.
EX:
Data Set 1:
1970 254.5
1980 264.5
1990 234.5
2000 234.7
Data Set 2:
1970 234.5
1980 234.6
2000 456.7
2010 234.7
I have to subtract Column 2 of data set one from Column 2 of data set 2. But in order to to this the first columns must match up. How can I write a code where it skips the entries where the entries in column one don't match up.
##### 1 CommentShow -1 older commentsHide -1 older comments
Azzi Abdelmalek on 28 Feb 2013
Post what should be the result

Sign in to comment.

### Accepted Answer

Sean de Wolski on 28 Feb 2013
D1 = [
1970 254.5
1980 264.5
1990 234.5
2000 234.7 ];
D2 = [
1970 234.5
1980 234.6
2000 456.7
2010 234.7];
%Where do they intersect?
[~,ia,ib] = intersect(D1(:,1),D2(:,1));
%Subtract intersecting parts:
dD = D1(ia,2) - D2(ib,2)
##### 1 CommentShow -1 older commentsHide -1 older comments
Sandy on 28 Feb 2013
Thanks! :)

Sign in to comment.

### More Answers (2)

Azzi Abdelmalek on 28 Feb 2013
a=[1970 254.5
1980 264.5
1990 234.5
2000 234.7]
b=[1970 234.5
1980 234.6
2000 456.7
2010 234.7]
idx=find(a(:,1)-b(:,1)==0)
c=b(:,2)
c(idx)=b(idx,2)-a(idx,2)
##### 0 CommentsShow -2 older commentsHide -2 older comments

Sign in to comment.

Sandy on 28 Feb 2013
Both of these work perfectly. Thanks!
##### 0 CommentsShow -2 older commentsHide -2 older comments

Sign in to comment.

### Categories

Find more on Introduction to Installation and Licensing in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!