Matlab sorting by last name into 26 substacks
1 view (last 30 days)
Show older comments
How can I sort names by last name. Suppose I have a list of names and I’d like to sort them by last name into substacks 1-26 for each letter of the alphabet.
Thanks
6 Comments
Walter Roberson
on 8 May 2020
Consider the name "Kim Jung". Which is the first name? What is the last name?
Answer: you don't know. If the person is Korean, then Kim is the last name and Jung is the first name. If the person is Germanic, then Kim is the first name and Jung is the last name.
Consider the name "José Maria Almeida de Pais Vieira". What is the last name?
Answers (1)
Arjun
on 5 Sep 2024
I see that you want to sort names based on the last name of the person into 26 sub-stacks, one for each alphabet.
I am assuming that last name would be appearing at the end of the name string. Based on the above assumption; to sort names by last name and organize them into sub-stacks for each letter of the alphabet in MATLAB, you can follow these steps:
- Extract Last Names: Parse the list to extract the last names.
- Sort Names: Sort the names based on the extracted last names.
- Organize into Sub-stacks: Divide the sorted list into sub-stacks based on the initial letter of the last name.
Kindly refer to the sample MATLAB Code:
% Sample list of full names
names = {'John Doe', 'Jane Smith', 'Alice Johnson', 'Bob Brown', 'Charlie Davis'};
% Initialize a cell array to hold the sub-stacks for each letter
substacks = cell(1, 26);
% Iterate over each name to extract the last name
for i = 1:length(names)
% Split the name into parts
nameParts = strsplit(names{i});
% Assume last part is the last name
lastName = nameParts{end};
% Determine the first letter of the last name
firstLetter = upper(lastName(1));
% Find the index for the substack (1 for 'A', 2 for 'B', ..., 26 for 'Z')
index = firstLetter - 'A' + 1;
% Append the full name to the appropriate sub-stack
substacks{index} = [substacks{index}, names(i)];
end
% Display the substacks
for i = 1:26
if ~isempty(substacks{i})
fprintf('Substack %c:\n', char('A' + i - 1));
disp(substacks{i});
end
end
To learn more about the “strsplit” function, kindly refer to the following documentation link: https://www.mathworks.com/help/releases/R2020a/matlab/ref/strsplit.html?searchHighlight=strsplit&s_tid=doc_srchtitle
I hope it will help!
1 Comment
Walter Roberson
on 5 Sep 2024
I am assuming that last name would be appearing at the end of the name string.
That turns out to be a fairly bad assumption when dealing with names other than white US and Canadian names
See Also
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!