Search code examples
arraysmatlabminanglesubtraction

find combination of min/max subtract between 2 arrays matlab


I have two arrays of angles: a=[140 360 170 3]; b= [12 270 0 21]; I need to find combination that will give me minimum when subtracting(/adding) elements of arrays. I'm doing this right now:

c = [ones(1,4)*a(1)-b; ones(1,4)*a(2)-b; ones(1,4)*a(3)-b; ones(1,4)*a(4)-b];

cc= abs(c);

[minNumk, minIndkl] = min(cc(:));
[rowk, colk] = ind2sub(size(cc), minIndkl);
cc(rowk,:)=[];
cc(:,colk)=[];

 [min2k,minInd2k]=min(cc(:));
 [row2k, col2k] = ind2sub(size(cc), minInd2k);
 cc(row2k,:)=[];
 cc(:,col2k)=[];

 [min3k,minInd3k]=min(cc(:));
 [row3k, col3k] = ind2sub(size(cc), minInd3k);
 cc(row3k,:)=[];
 cc(:,col3k)=[];
 min4k= cc;
total=minNumk+min2k+min3k+min4k

Question. Is there any way of doing it in a more concise way? Also I am thinking do I need to use mod(,360) here?

EDITED: if the element was used(subtracted) then it cannot be used anymore. (Thus,the whole row and column is deleted.)

Thanks in advance!!!

Any advice will be very much appreciated! Happy 10 000 000! :)


Solution

  • If I understand correctly, you want to try all permutations of one of the vectors and minimize (over all permutations) the sum (over vector entries) of absolute values of the differences between the vectors:

    result_total = min(sum(abs(bsxfun(@minus, a, perms(b))), 2));
    

    To get the invididual differences that minimize the sum of absolute differences:

    d = bsxfun(@minus, a, perms(b));
    [result_total, ind] = min(sum(abs(d), 2));
    result_indiv = d(ind,:);
    

    If you want to consider the differences to be in the range 0-360, use mod (and then you don't need abs):

    d = mod(bsxfun(@minus, a, perms(b)),360);
    [result_total, ind] = min(sum(d, 2));
    result_indiv = d(ind,:);