MATLAB: Sort unique string/number column based on last 2 characters

sort

How do I sort a column based on the last 2 characters while maintaining the unique string/number order? I want each group of unique strings/numbers to be reoriganized based on the last 2 characters in this order:
1. ut, fx, os, st, ng (doesn't matter what the order here)
2. ub
3. uu
4. uj
5. nh
Here's parts of the column (it's actually 67×1 cell)
ap12qw_nh
ap12qw_ub
ap12qw_uj
ap12qw_uu
qw54rt_ub
qw54rt_ut
zx23vb_fx
zx23vb_ng
zx23vb_nh
zx23vb_os
zx23vb_st
zx23vb_ub
zx23vb_uj

Best Answer

Here is one way:
% The guide to ordering the letter-pairs. (Although the order of the first few letter-pairs
% doesn't matter, it seemed easier to just sort them anyway.)
order_guide = {'ut', 'fx', 'os', 'st', 'ng', 'ub', 'uu', 'uj', 'nh'};
% Input
input = {'ap12qw_nh','ap12qw_ub','ap12qw_uj','ap12qw_uu','zx23vb_fx'}'; % I didn't include them all
% Pull the last two characters of the input
last_two = cellfun(@(x)x(end-1:end),input,'UniformOutput',false);
% Identify which letter-pair the input belongs to, in order
[tf,indexOrder] = ismember(last_two,order_guide);
% Sort the input accordingly
[~,sorting_order] = sort(indexOrder);
sorted_input = input(sorting_order);