필터 지우기
필터 지우기

Having vector sorted by using While Loops + Diff()

조회 수: 3 (최근 30일)
Brandon Tsang
Brandon Tsang 2020년 5월 21일
답변: Ayush Goyal 2020년 6월 19일
Hi. My function has to sort a numerical vector by using only while loops, diff(),any(), or all()
  • Must Use a While Loop
  • No For Loop
n=length(v);
while ~any(diff(v) >= 0) % detects if vector is sorted.
i1=ceil(n*rand(1));
i2=ceil(n*rand(1));
temp=v(i1);
v(i1)=v(i2);
v(i2)=temp;
end
order = v;
  댓글 수: 4
Walter Roberson
Walter Roberson 2020년 5월 22일
That's better, but what question is being asked?
Walter Roberson
Walter Roberson 2020년 5월 22일
I see you edited what you posted, but you still have not asked a question. You made some statements, but you did not ask anything from us.

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

답변 (1개)

Ayush Goyal
Ayush Goyal 2020년 6월 19일
From my understanding of the question you want to write a function to sort vector using only while loops, diff(), any(), or all() but you are getting wrong outputs. There is error in your code in the condition part of while loop and to sort the vector in increasing order you should use the following code:
n=length(v);
while any(diff(v) <= 0) % Change this line
i1=ceil(n*rand(1));
i2=ceil(n*rand(1));
temp=v(i1);
v(i1)=v(i2);
v(i2)=temp;
end
order = v;

카테고리

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