Is there a nice way to test whether two arrays are proportional in MATLAB? Something like the isequal
function but for testing for proportionality.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With