How would one reverse the order of an array using a while loop?

7 vues (au cours des 30 derniers jours)
Justin Keach
Justin Keach le 30 Oct 2016
Commenté : Walter Roberson le 31 Oct 2016
For this homework question I am asked to write a program using the while loop that will display a given row or column vector in reverse.

Réponse acceptée

Asad (Mehrzad) Khoddam
Asad (Mehrzad) Khoddam le 30 Oct 2016
if v is the vector:
n=length(v);
while n>0
disp(v(n));
n=n-1;
end
  2 commentaires
Justin Keach
Justin Keach le 30 Oct 2016
Thank you! That works, but now I need to convert each output back into a vector so that if v=[1 2 3 4] my answer will return as v1= [4 3 2 1]. My current attempts have only returned my row vector as the final element/final output of the loop.
Justin Keach
Justin Keach le 30 Oct 2016
v=Array2;
k=length(v);
while k>0;
disp(v(k));
k=k-1;
end
disp(['The original array was: ' mat2str(v)]);

Connectez-vous pour commenter.

Plus de réponses (1)

Walter Roberson
Walter Roberson le 30 Oct 2016
Supposed the length of your vector is L. Then you want to copy position j to position L-j+1 in the new vector. For example, length 6, position 1 gets written to position 6-1+1 = 6; position 2 gets written to position 6-2+1 = 5, position 3 to position 6-3+1 = 4, and so on.
  2 commentaires
Justin Keach
Justin Keach le 31 Oct 2016
How would you implement this into a while loop? I understand what you mean, but I'm not sure how to write it in a program.
Walter Roberson
Walter Roberson le 31 Oct 2016
In your code above,
k=length(v);
and then
L = k;
and then entry k of input corresponds to entry L-k+1 of output.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by