MATLAB: Can we do something like this similar to union()

MATLABunion

Currently union() returns non-repeated result. But I want repeat result like the following,
>> myunion([2 3 3 5], [1 3 5])
ans =
1 2 3 3 5
I can write for-loop and if-statement to do this. But is there a better or easy way?
Thanks Kevin

Best Answer

Method one: unique, arrayfun, ones:
>> A = [2,3,3,5];
>> B = [1,3,5];
>> fun = @(n)n*ones(1,max(nnz(A==n),nnz(B==n)));
>> C = arrayfun(fun,unique([A(:);B(:)]),'uni',0);
>> U = [C{:}]
U =
1 2 3 3 5
Note: the arrayfun call is just for convenience, not for speed!
Method two: unique, histc, repelem:
>> A = [2,3,3,5];
>> B = [1,3,5];
>> Q = unique([A(:);B(:)].');
>> repelem(Q,max([histc(A,Q);histc(B,Q)]))
ans =
1 2 3 3 5