MATLAB Return value of first non-empty argument (built-in COALESCE function)

750 views Asked by At

Is there something inbuilt in MATLAB which functions similar to the SQL COALESCE function. I want that function to return the first 'existing' value from all the arguments.
For example,

clear A B; C=10; COALESCE(A,B,C)

should return value of C (because A and B are unassigned/don't exist).
I know it would be very easy to code, and I am just being lazy here. But, I would be surprised if MATLAB doesn't have a similar function.

1

There are 1 answers

1
Matt On

As far as I know there is no built-in function for that. But you can easily write your own.

Note that it is not possible in Matlab to pass a variable that has not been defined prior of using it. Therefore your proposed call clear A B; C=10; COALESCE(A,B,C) is invalid and will throw an error. Instead we can define an empty variable using var=[].

The following code creates two empty variables A, B and and assigns C=10. Inside the function coalesce we assume at the beginning that all variables are empty. In the for-loop we return the first non-empty variable. In the version without for-loop we get the index of the first non-zero element and then return the corresponding content of the cell if a non-zero element exists.

If you want the function to be accessible from everywhere within Matlab, see the documentation here.

function testcoalesce
    A = [];
    B = [];
    C = 10;
    COALESCE(A,B)
    COALESCE(A,B,C)
end

% with for-loop (much faster)
function out = COALESCE(varargin)
    out = [];
    for i = 1:length(varargin)
       if ~isempty(varargin{i})
           out = varargin{i};
           return;
       end
    end
end

% without for-loop (slower)
function out = COALESCE(varargin)
    out = [];
    ind = find(cellfun('isempty', varargin)==0, 1);
    if ~isempty(ind); 
        out = varargin{ind};
    end
end

The output is as expected:

ans =
     []
ans =
    10

Timing the two functions showed, that the first solution using the for-loop is approximately 48% faster than the function without loop.
(10 samples, 1'000'000 iterations, 3 variables & 20 variables)