Having vector sorted by using While Loops + Diff()
Mostra commenti meno recenti
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 Commenti
Walter Roberson
il 21 Mag 2020
[] is a built-in function.
numel() is a built-in function.
/ is a built-in function.
diff() is a built-in function.
: (colon) is a built-in function.
Indexing is a built-in function.
< is a built-in function.
subtraction is a built-in function.
It turns out that it is not possible to sort a vector without using built-in functions.
Brandon Tsang
il 21 Mag 2020
Walter Roberson
il 22 Mag 2020
That's better, but what question is being asked?
Walter Roberson
il 22 Mag 2020
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.
Risposte (1)
Ayush Goyal
il 19 Giu 2020
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;
Categorie
Scopri di più su Shifting and Sorting Matrices in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!