Effacer les filtres
Effacer les filtres

I need help creating a function for taking an array and reversing it and i have to use a for loop. I have looked online but i really dont know what i am doing?

9 vues (au cours des 30 derniers jours)
function result = reverse_array(array)
result = array;
for(index = zero(1,length(array)))
index = reverse_array(index) = array(length(array)-index+1);
end
end

Réponses (1)

Evan
Evan le 12 Fév 2015
Modifié(e) : Evan le 12 Fév 2015
There are built-in functions for this, such as fliplr and rot90.
However, if you want to use a loop, think about the process you want to do, step-by-step. You want to create a new array that is a flipped version of an array you send into the function. So you want to access each element of the array in reverse, from end to beginning, and assign it to your new array, from beginning to end.
function y = flip_array(x)
n = ?
x_indices = ?
for y_index = 1 : n
x_index = x_indices(y_index);
y(y_index) = x(x_index);
end
end
You just need to find a a value n that tells you how long your new array is going to be, then an array of x indices that gives you want you want. Think about how the colon ( : ) operator can be used, and remember that you can use it to create arrays that count up or down.
  3 commentaires
nick sorge
nick sorge le 12 Fév 2015
so for n would i just put in the random walk function that i already created or how would i do that if the random walk array can change size?
Evan
Evan le 13 Fév 2015
n tells you how many iterations the loop goes through. You need to pass over each element in your array, however long it is. So n isn't the array itself, but information about that array. You need some function (a builtin matlab function) that will get you this information.

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