Search code examples
matlabinterpolationminimization

Finding nearest value of (x,y) with respect to two matrices X and Y


I have two matrices n*n (in this example n = 51). One matrix is named Q1. Second matrix is Q2. Both matrices correspond to probabilities (i.e between [0,1]). In theory Q1+Q2 = 1 (but it is not necessarily so in this example as I removed some values and other Q3 Q4 etc. to simplify the question with this example).

I'm trying to find the indexes in each row (or column) such that the value of Q1 is nearest to q_val(1), and the value of Q2 is nearest to q_val(2).

the data can be found here: http://www.filedropper.com/stackoverflowdata

When I calculate the nearest value in each matrix separately, I eventually get two curves (See below in figure, or copy paste the code and plot). However I would like to find a single curve which is nearest.

How can I find a single set of indexes in Q1 and Q2 (for each row or column) which is nearest to q_val?

    q_val = [0.41 0.52];
    for i = 1:length(u_vec)
        tmp1 = abs(Q1(:,i)-q_val(1));
        tmp2 = abs(Q2(:,i)-q_val(2));
        ind1 = find(tmp1==min(tmp1));
        ind2 = find(tmp2==min(tmp2));
        v1(i) = v_vec(ind1);
        v2(i) = v_vec(ind2);
    end
    
    [U,V] = meshgrid(u_vec,v_vec);
    figure
    subplot(1,2,1)
    hold on
    pcolor(U,V,Q1)
    plot(u_vec,v1,'k',u_vec,v2,'r','linewidth',1.5)
    shading interp
    xlim([2 2.2])
    title('Q1')
    subplot(1,2,2)
    hold on
    pcolor(U,V,Q2)
    plot(u_vec,v1,'k',u_vec,v2,'r','linewidth',1.5)
    shading interp
    xlim([2 2.2])
    xlabel('u');ylabel('v')
    title('Q2')

enter image description here


Solution

  • To solve this problem, it is important to first define a certain mathematical criterion for measuring the proximity of one value to two other values. For example, this criterion could be the sum of the distances between the first value and the other two values.

    If you do not care that the answer must be selected from v_vec, you can simply calculate the average of the two values that each minimize distance to Q1 and Q2 (v3). Otherwise you can find the value that minimizes the sum of the two distances (v4).

    [~, ind1] = min(abs(Q1-q_val(1)), [], 1);
    [~, ind2] = min(abs(Q2-q_val(2)), [], 1);
    
    v1 = v_vec(ind1);
    v2 = v_vec(ind2);
    v3 = (v1+v2)/2;
    
    [~, ind4] = min(abs(Q1-q_val(1))+abs(Q2-q_val(2)), [], 1);
    v4 = v_vec(ind4);
    

    enter image description here