This is machine translation

Translated by Microsoft
Mouse over text to see original. Click the button below to return to the English verison of the page.


Merging two ordered lists

MuPAD® notebooks are not recommended. Use MATLAB® live scripts instead.

MATLAB live scripts support most MuPAD functionality, though there are some differences. For more information, see Convert MuPAD Notebooks to MATLAB Live Scripts.


listlib::merge(list1, list2, <function>)


listlib::merge(list1, list2) merges both lists into one list.

With the third optional argument a function can be given that compare the elements of the lists and therewith determines the order of the elements. The given function is called with two elements and have to return TRUE, if the two elements are in the right order, otherwise FALSE (see next paragraph).

The given function is called step by step with an element of the first list as first argument and an element of the second list as second argument, until it returns FALSE. Then the element of the second list is inserted into the first list in front of the last proved element (see Example 2).

    Note:   The lists must be ordered with regard to the order function, otherwise the elements could be inserted at the wrong place.

If no third argument is given the function _less is used. If no order of the elements with regard to _less is defined, a function must be given, otherwise an error appears. The system function sysorder always can be used.


Example 1

Merging two ascending ordered lists:

listlib::merge([1, 3, 5, 7], [2, 4, 6, 8])

Merging two descending ordered lists:

listlib::merge([7, 5, 3, 1], [8, 6, 4, 2], _not@_less)

Example 2

The following example shows, how expressions can be ordered by a user defined priority. This order is given by the function named priority, which returns a smaller number, when the expression has a type with higher priority:

priority := X -> contains(["_power", "_mult", "_plus"], type(X)):
priority(x^2), priority(x + 2)

The function sortfunc returns TRUE, if the both given arguments are in the right order, i.e., the first argument has a higher (or equal) priority than the second argument:

sortfunc := (X, Y) -> bool(priority(Y) > priority(X)):
sortfunc(x^2, x + 2), sortfunc(x + 2, x*2)

Now the both lists are merged with regard to the given priority:

listlib::merge([x^y, x*2, -y], [x^2, x*y, x + y], sortfunc)

delete priority, sortfunc:


list1, list2

A MuPAD® list


A function that determines the merging order

Return Values

Ordered list that contains the elements of both lists

See Also

MuPAD Functions

Was this topic helpful?