This functionality does not run in MATLAB.
coerce(object, T) tries to convert object into an element of the domain T.
If this is not possible or not implemented, then FAIL is returned.
Domains usually implement the two methods "convert" and "convert_to" for conversion tasks.
coerce uses these methods in the following way: It first calls T::convert(object) to perform the conversion. If this call yields FAIL, then the result of the call object::dom::convert_to(object, T) is returned, which again may be the value FAIL.
To find out the possible conversions for the object or which conversions are provided by the domain T, please read the description of the method "coerce" or "convert", respectively, that can be found on the help page of the domain T, and the description of the method "convert_to" on the help page of the domain of object.
Only few basic domains currently implement the methods "convert" and "convert_to".
Use the function expr to convert an object into an element of a basic domain.
Note that often a conversion can also be achieved by a call of the constructor of the domain T. See Example 3.
We start with the conversion of an array into a list of domain type DOM_LIST:
a := array(1..2, 1..3, [[1, 2, 3], [4, 5, 6]])
The conversion of an array into a polynomial is not implemented, and thus coerce returns FAIL:
One can convert a one- or two-dimensional array into a matrix, and vice versa. An example:
A := coerce(a, matrix); domtype(A)
The conversion of a matrix into a list is also possible. The result is then a list of inner lists, where the inner lists represent the rows of the matrix:
coerce([1, 2, 3, 2], DOM_SET)
Any MuPAD® object can be converted into a string, such as the arithmetical expression 2*x + sin(x^2):
coerce(2*x + sin(x^2), DOM_STRING)
f := factor(x^2 + 2*x + 1); domtype(f)
This domain implements the conversion routine "convert_to", which we can call directly to convert the factorization into a list (see factor for details):
However, it is more convenient to use coerce, which internally calls the slot routine Factored::convert_to:
Note that often a conversion can also be achieved by a call of the constructor of a domain T. For example, the following call converts an array into a matrix of the domain type Dom::Matrix(Dom::Rational):
a := array(1..2, 1..2, [[1, 2], [3, 4]]): MatQ := Dom::Matrix(Dom::Rational):
The call MatQ(a) implies the call of the method "new" of the domain MatQ, which in fact calls the method "convert" of the domain MatQ to convert the array into a matrix.
Here, the same can be achieved with the use of coerce:
A := coerce(a, MatQ); domtype(A)
Note that the constructor of a domain T is supposed to create objects, not to convert objects of other domains into the domain type T. The constructor often allows more than one argument which allows to implement various user-friendly ways to create the objects (e.g., see the several possibilities for creating matrices offered by matrix).