How to compare elements in several vectors (of different sizes) against each other?

I have three vectors in Matlab that can be of different sizes. I want to compare the values ​​in each vector with all the other values ​​in other vectors and save only those values ​​that are “closed” in 2 out of 3 vectors. And “keep”, I mean, I take the average of close values.

For instance:

a = [10+8i, 20];
b = [10+9i, 30, 40+3i, 55];
c = [10, 60, 41+3i];

If I set proximity tolerances to preserve only values ​​that are inside, say, values ​​of 1.5 from each other, then the following values ​​should be marked as close:

  • 10 + 8i vs 10 + 9i
  • 40 + 3i vs 41 + 3i

Then the routine should return a length vector that contains the average value for each of these sets of numbers:

finalVec = [10+8.5i,40.5+3i];

Matlab? , ?

+4
2

:

a = [10+8i, 20];
b = [10+9i, 30, 40+3i, 55];
c = [10, 60, 41+3i];

M1 = compare_vectors(a , b);
M2 = compare_vectors(a , c);
M3 = compare_vectors(b , c);
finalVec = [M1, M2 , M3]


function M = compare_vectors(a , b)

    % All combinations of vectors elements
    [A,B] = meshgrid(a,b);
    C = cat(2,A',B');
    D = reshape(C,[],2);

    % Find differences lower than tolerance
    tolerance = 1.5
    below_tolerance = abs(D(:,1) - D(:,2)) < tolerance ;

    % If none, return empty
    if all(below_tolerance== 0)
        M = [];
        return
    end

    % Calculate average of returned values
    M = mean(D(below_tolerance,:));

end
+3
% your data   
a = [10+8i, 20];
b = [10+9i, 30, 40+3i, 55];
c = [10, 60, 41+3i];
tol = 1.5;

% call the function with each combination of vectors and concatenate the results
finalVec = cell2mat(cellfun(@closepoints, {a, a, b}, {b, c, c}, {tol, tol, tol}, 'Uni', 0))

function p = closepoints(a, b, tol)
    % find the pairs of indexes of close points 
    %    the bsxfun() part calculates the distance between all combinations of elements of the two vectors
    [ii,jj] = find(abs(bsxfun(@minus, a, b.')) < tol);
    % calculate the mean
    p = (a(jj) + b(ii))/2;
end

, cellfun() , for. , , , .

+1

Source: https://habr.com/ru/post/1695102/


All Articles