Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if arrays are proportional

Tags:

arrays

matlab

Is there a nice way to test whether two arrays are proportional in MATLAB? Something like the isequal function but for testing for proportionality.

like image 564
RGWinston Avatar asked Dec 24 '22 04:12

RGWinston


2 Answers

One heuristic way to do this would be to simply divide one array by another element wise, and ensure that the largest and smallest values within this result are within some tolerance. The degenerate case is when you have zeroes in the arrays. In this case, using max and min will not affect the way this algorithm works because those functions ignore nan values. However, if both A and B are zero arrays, then there are an infinite number of scalar multiples that are possible and so there isn't one answer. We'll set this to nan if we encounter this.

Given A and B, something like this could work:

C = A./B; % Divide element-wise
tol = 1e-10; % Divide tolerance

% Check if the difference between largest and smallest values are within the
% tolerance
check = abs(max(C) - min(C)) < tol;

% If yes, get the scalar multiple
if check
    scalar = C(1);
else % If not, set to NaN
    scalar = NaN;
end
like image 86
rayryeng Avatar answered Jan 01 '23 14:01

rayryeng


If you have the Statistics Toolbox, you can use pdist2 to compute the 'cosine' distance between the two arrays. This will give 0 if they are proportional:

>> pdist2([1 3 5], [10 30 50], 'cosine')
ans =
     0

>> pdist2([1 3 5], [10 30 51], 'cosine')
ans =
     3.967230676171774e-05

As mentioned by @rayryeng, be sure to use a tolerance if you are dealing with real numbers.

like image 29
Luis Mendo Avatar answered Jan 01 '23 16:01

Luis Mendo