Sorting a cell of strings using a certain character position

Q
Quincy · Jan 8, 2021 · 2.3K views
Question
I have a variable called var= vart=[{'Ice011_L_3of3m.mat''}; {'Ice011_P_1of3m.mat'} ;{'Ice011_P_2of3m.mat'}] We would need to sort the strings in the cell array using the 10th character of each string, so we would get the following result   var_sorted =[{'Ice011_P_1of3m.mat'}; {'Ice011_P_2of3m.mat'} ;{'Ice011_L_3of3m.mat'}]
Expert Answer
Profile picture of John Williams
John Williams PhD Expert
Answered Aug 22, 2026
Simpler in two lines:
 
 
vart = {'Ice011_L_3of3m.mat';'Ice011_P_1of3m.mat';'Ice011_P_2of3m.mat'}
[~,idx] = sort(cellfun(@(v)v(10),vart));
vart = vart(idx)

If you need to match more than one digit you could use a regular expression, e.g.:

[~,idx,] = sort(str2double(regexp(vart,'(?<=_)\d+','match','once')));
100% Run Guarantee 3-Hour Fast-Track Delivery

Need a Custom Version or Complete Simulation for This Problem?

Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.

Tested on MATLAB R2024b / R2026a
Turnitin 0% Plagiarism Report
Free 7-Day Revisions Guarantee
Have a different question? Ask here

Get a Free Consultation or a Sample Assignment Review!