sort vector elements under given restrictions

조회 수: 1 (최근 30일)
oxy
oxy 2014년 3월 19일
댓글: zepp 2014년 3월 20일
Hi guys,
i have the vector v=[1 2 3 4 5]
wanna resort it so that v(3) and v(5) comes first:
v=[3 5 others] % 'others' has any order
How can i do that? The problem here is exactly this: how to write 1:5 but missing 3 and 5 .
Any idea? thx...
-----------------------------------------------------------------------------------------
PS: this question is related to
The point relating to this cited question is that i can find all combinations (just for-loop), but i cannot arrange the rest of the dimensions. Thus this present question.
Thx...

채택된 답변

zepp
zepp 2014년 3월 19일
You can create a logical array (same length as v) with 1's for the positions you want (say, 3 and 5) and 0's for the rest and use that to refer to the indices.
v = [1 2 3 4 5]
ind = [0 0 1 0 1]
v = [v(ind==1) v(~ind==1)]

추가 답변 (1개)

oxy
oxy 2014년 3월 20일
편집: oxy 2014년 3월 20일
Great! Thx!
Just another question: This is the way I've been doing it on octave. I wander why it doesnt work in matlab!!! :-/
vector2sort= 1:6
n=length(vector2sort)
a=2; b=4 % i.e. I wanna the 2nd and 4th elements of vector2sort first
[a b (1:n)( (1:n)!=a & (1:n)!=b )] % this is how we sort it
Why it does not work in matlab?!! Is there a way to do it more simila?
thx 4 your wisdom!
  댓글 수: 1
zepp
zepp 2014년 3월 20일
The concept is fine, but you can't reference array elements like that in Matlab.
Try this out:
v = 1:6;
a = 2; b = 4;
sortedv = [a b v(v~=a & v~=b)];

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by