# Subtracting equal elements of one array from another array of a different size

10 views (last 30 days)
Jerad King on 22 Apr 2022
Commented: Jerad King on 22 Apr 2022
Howdy,
I am having an issue that I would like some help with.
I have two arrays, one is 13x9 and the other is 7x9. What I would like to do is subtract elements of the smaller array third column from the larger array third column given that the elements in the fourth column are equal to each other. I have already reduced the dimensions of the larger array to ensure all elements of the smaller arrays fourth column are present, but I'm getting array dimension mismatch errors.
Something like...
arr1(:,3) - arr2(:,3)
if arr2(:,4) == arr1(:,4)
= newarr(:,:)
Matt J on 22 Apr 2022
I recommend providing an example to show what you mean along with the desired output. Perhaps with fewer rows and with only 2 columns (since only columns 3-4 matter for your problem).
Jerad King on 22 Apr 2022
texmp =
5.83 188.00
5.36 51.00
5.32 45.00
5.42 43.00
5.62 123.00
8.00 147.00
5.03 109.00
exmp =
5.85 188.00
5.29 45.00
5.42 43.00
5.35 51.00
5.32 45.00
5.41 43.00
5.14 109.00
5.40 51.00
5.35 45.00
5.41 43.00
5.91 188.00
5.34 51.00
5.30 45.00
so if texmp(n,2) == exmp(n,2)
then texmp(n,1) - exmp(n,1)
with final output being something like
fexmp =
-0.02 188.00
0.00 45.00
-0.01 43.00.....
I hope this helps, thx!

Jeffrey Clark on 22 Apr 2022
One way to allow MATLAB to compare different sized vectors is to have one be a column and the other be a row. Assuming we are still talking about columns 3 and 4 in the 13x9 exmp and 7x9 texmp, you want to change the test for column 4 to be something like this: indexmap = exmp(:,4)==texmp(:,4)'; note the apostrophe changing the texmp column vector to be a row vextor - indexmap will be a 13x7 logical showing in column 1 the indexes of the rows of exmp that need to be modified by the first row data of texmp, and so on for the 2-7 columns. (Note that 2 rows of texmp will not be applied to any of the rows of exmp.)
So then you can loop thru the indexmap columns to apply the subtractions, like this (but you may find a better way now that you have this new tool :)
j = 1;
for i=indexmap;
exmp(i,3) = exmp(i,3)-texmp(j,3);
j = j+1;
end
Jerad King on 22 Apr 2022
This worked perfectly, thank you so much!

### Categories

Find more on Matrix Indexing in Help Center and File Exchange

R2021b

### Community Treasure Hunt

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

Start Hunting!