0

I have two arrays in matlab/octave a1 is calculated and a2 is given. How can I create a 3rd array a3 that compares a1 to a2 and shows the values that are missing in a1?

a1=[1,4,5,8,13]
a2=[1,2,3,4,5,6,7,8,9,10,11,12,13]
a3=[3,6,7,9,10,11,12]

Also can this work for a floating point number say if a1=[1,4,5,8.6,13] or would I have to convert a1 to integers only.

Thanks

Rick T
  • 3,349
  • 10
  • 54
  • 119
  • Always be careful when comparing floating point numbers: [Why is 24.0000 not equal to 24.0000 in MATLAB?](http://stackoverflow.com/questions/686439/why-is-24-0000-not-equal-to-24-0000-in-matlab), [How do I compare all elements of two arrays in MATLAB?](http://stackoverflow.com/questions/2202641/how-do-i-compare-all-elements-of-two-arrays-in-matlab) – Amro Oct 15 '11 at 00:25

2 Answers2

4

setdiff returns the elements of one array that aren't in another. This will work with floating-point values, but requires equality.

a3 = setdiff(a2, a1)
Nzbuu
  • 5,241
  • 1
  • 29
  • 51
  • I misread the problem statement, so the OP can ignore my previous solution using `intersect`. This is the right solution. – Chris A. Oct 10 '11 at 01:16
1
function missing = comparray(a1, a2)
% array of numbers that are missing from input
missing = []
% for each element in a2, check if it's in a1
for ii=1:1:length(a2)
    num = a2(ii);
    deltas = abs(a1 - num);
    if min(deltas) ~= 0
        missing = [missing, num];
    end
end

Floating point numbers can be tricky. To get the above code to work with them, check min(deltas) > 0.001 (or a suitable very small value given the precision of your input numbers). For more information, see here

user670416
  • 736
  • 4
  • 12