Is there a succinct way in Octave to compare two vectors using dictionary order (lexicographic) order?
i.e. I'd like to compare two vectors a
, b
by the first element, return result if they differ; otherwise compare the second element, and so on..
For example, if a = [0 1 5]
, b = [0 2 1]
, I'd like to have
a <? b
for some operator/function <?
to return true.
If I simply do a < b
, this will return a vector of logical values.
ans =
0 1 0
The following will work for both MATLAB and Octave...
You can create a comparison function using find
like so:
lexlt = @(a, b) find([a < b true], 1) < find([a > b true], 1);
It will return true if the first vector argument is lexographically less than the second, and false otherwise (if it's greater than or equal to it). For example:
>> a = [0 1 5];
>> b = [0 2 1];
>> lexlt(a, a)
ans =
logical
0
>> lexlt(a, b)
ans =
logical
1
>> lexlt(b, a)
ans =
logical
0
And here's the corresponding function for a "greater than" comparison (i.e. the first argument is lexographically greater than the second):
lexgt = @(a, b) find([a > b true], 1) < find([a < b true], 1);