How do I manipulate arrays more efficiently?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
tr4nshum4n
am 5 Mai 2016
Beantwortet: CS Researcher
am 5 Mai 2016
I am in the habit of using nested for loops to sort arrays. I suspect there are methods that are much simpler and don't require as much debugging.
The following is an example from a Cody problem. The function is to sort elements of vector a by their distance from number t. The name of the problem was "target sorting". Elements that are closest to t will be nearest the end of the vector. Elements that are farther from t will be nearest the beginning of the vector. Here is a link to the problem.
And here is my code:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% Code %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function b = targetSort(a,t)
b = [];
for( i=1 : numel(a) )
shell = abs( t-a(i) )
if( numel(b) == 0)
b = [a(i)]
else
for( j=1: numel(b) )
if( shell > (abs(t - b(1))) )
b = [a(i) b]
break
end
k = j+1
if( j==numel(b) )
b = [b a(i)]
elseif( ...
and( ...
( shell <= abs(t - b(j )) ), ...
( shell >= abs(t - b(k)) ) ...
)...
)
b = [b(1:j) a(i) b(k:end ) ]
break
end
end
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
0 Kommentare
Akzeptierte Antwort
CS Researcher
am 5 Mai 2016
How about this:
b = abs(a-t);
[~,l] = sort(b,'descend');
c = a(l);
Hope this helps!
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!