Finding values that aren't in an array in matlab/octave [duplicate]
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
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)
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
精彩评论