Alphabetical Sorting (case insensitive)

11 ビュー (過去 30 日間)
Aiden Chrisan
Aiden Chrisan 2018 年 4 月 19 日
コメント済み: Walter Roberson 2025 年 2 月 21 日

Heyy everyone, Having small issue with my code, where i want to assort an array of words in alphabetical order (with specific case insensitive sorting). My code is;

A = ["help" ; "MATLAB" ; "anyTIME" ; "matrix" ; "alGEBra"];
[M,N]=size(A);
for i = 2:N
    char = A(i,:);
    j = i-1;
      A_j=A(j+1,:);
      A(n+1:i)=A_j(A_j>char);
      j=j-max(A_th);
      A(j+1,:) = char;
end
disp(A);

it assorts the words, but not correctly. I can successfully do this sorting with numbers no problem. And i can sort the words alphabetically with the output case sensitive(have a couple different codes but wont attach them coz i dont want to bore you lovely people). but getting the output as alphabetical AND case insensitive is proving much more problematic (NOTE: i know you could use the sort function, but i want to do it with this one for loop). Any help is much appreciated <3

  1 件のコメント
Stephen23
Stephen23 2018 年 4 月 19 日
編集済み: Stephen23 2018 年 4 月 19 日
The first line
A = ["help" ; "MATLAB" ; "anyTIME" ; "matrix" ; "alGEBra"];
defines a 5x1 string array. Then you measure the size of that string array using
[M,N]=size(A);
So given that N==1, I don't see how this for loop will ever iterate even once:
for i = 2:N
Also, if A is really a string array, then char = A(i,:); is not a char vector but another string array.

サインインしてコメントする。

回答 (2 件)

Suraj Mankulangara
Suraj Mankulangara 2018 年 4 月 23 日
Hello Aiden,
Here's a simple (and likely not very efficient) bubblesort implementation of case-insensitive string array sorting:
A = ["help" ; "MATLAB" ; "anyTIME" ; "matrix" ; "alGEBra"];
[M,N]=size(A);
for i = 1:M-1
for j = 1:M-1
curr = A(j);
next = A(j+1);
if upper(curr) > upper(next)
A(j) = next;
A(j+1) = curr;
end
end
end
disp(A);
I do not quite understand why you do not want to use the in-built MATLAB "sort" function to achieve this. There is no need to reinvent the wheel. Also, the in-built functions are likely to be much more efficient and optimized. You could do case-insensitive sorting using the "sort" function by converting all characters to uppercase, like this:
[~,idx]=sort(upper(A))
out=A(idx)

Adam Danz
Adam Danz 2025 年 2 月 20 日
> I want to assort an array of words in alphabetical order with case insensitive sorting
A = ["help" ; "MATLAB" ; "anyTIME" ; "matrix" ; "alGEBra"];
[~,sortIdx] = sort(lower(A));
ASort = A(sortIdx)
ASort = 5x1 string array
"alGEBra" "anyTIME" "help" "MATLAB" "matrix"
  1 件のコメント
Walter Roberson
Walter Roberson 2025 年 2 月 21 日
I experimented with using the ComparisonMethod option to sort(), but it is not recognized for the case of sorting strings.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by