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.
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 usingvar=[]
.The following code creates two empty variables
A
,B
and and assignsC=10
. Inside the functioncoalesce
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.
The output is as expected:
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)