Need help with sorting a string when a numeric vector moves also . Can't use the sort or min function
2 views (last 30 days)
Show older comments
So im trying to sort a string basec on how to Times variable moves in Task 2, i figured out how to sort the Times in ascending order but i want the Names variable to move concurrent with where the Times numbers go can anyone help?
%Task 1
load('Processes_4.mat');
[ROW,COL] = size(Names);
[r,c]= size(Times);
str1 = isvector(Names);
str=isstring(Names);
vect= isnumeric(Times);
vect1 =isvector(Times);
if vect~=1 || vect1 ~=1 || r ==1 && c ==1
Times_ =1;
else
Times_ =0;
end
if str1 ~=1 || str ~=1 || ROW ==1 && COL ==1
names_ =1;
else
names_ =0;
end
if Times_ == 1 && names_ ==1
error('Both provided variables is invalid')
end
if str~=1 || vect1 ~=1 || r==1 && c==1
error('Times variabble is invalid')
end
if str~= 1 || str~=1 || ROW ~=1 && COL ~=1
error('Names variable is invalid');
end
%Task 2
T= length(Times);
N=length(Names);
for i = 1:T
for j= 1:T
if Times(j) > Times(i)
Newtime=Times(j);
Times(j) = Times(i);
Times(i) =Newtime;
if Names(Times(j)) > Names(Times(i))
Newname= Names(Times(j));
Names(Times(j)) = Names(Times(i));
Names(Times(i)) =Newname;
end
end
end
end
0 Comments
Answers (1)
Ameer Hamza
on 4 Apr 2020
Edited: Ameer Hamza
on 4 Apr 2020
I cannot run your code with the mat file, so it is unclear what you are trying to do. But if you want to sort a string array, in the same order as a numeric array then try something like this
str = ["dog", "fox", "Quick", "brown", "jumps", "over", "lazy", ];
num = [7 3 1 2 4 5 6];
A = [num' (1:numel(num))'];
A(num,:) = A;
str = str(A(:,2));
4 Comments
Ameer Hamza
on 4 Apr 2020
Ah! I missed that you don't want to use sort() function. Check the updated answer.
Ameer Hamza
on 4 Apr 2020
Edited: Ameer Hamza
on 4 Apr 2020
Note that this will only work if the numeric vectors have all numbers from 1 to n.
See Also
Categories
Find more on Loops and Conditional Statements 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!