Initiating a For Loop!

3 visualizaciones (últimos 30 días)
GoodVibesVeal
GoodVibesVeal el 9 de Oct. de 2016
Respondida: Walter Roberson el 9 de Oct. de 2016
CS 1371, the class for Matlab, has been fairly easy up to this week, but, for some reason, I do not understand iteration. My question is about For Loops. My code is supposed to run from the beginning of a vector to the end of a vector, using those values to index an array, but I can only get it to index the first value, and it is probably because I am not initiating my For Loop correctly. The variable "moves" is a 2Xn vector, and each column is used to find the value of that position in "map" I will post the relevant section of my code below:
n=[];
vec=moves(1,length(moves));
for arr=vec;
ogpos=moves(:,1);
ogposcat=ogpos';
movenext=(ogposcat(1),ogposcat(2));
movesnext= map(movenext);
end
I greatly appreciate any of your help!!!

Respuesta aceptada

Walter Roberson
Walter Roberson el 9 de Oct. de 2016
You indicate that moves is 2 x n. Provided that n >= 2, length(moves) would be 2, as length() returns 0 if any dimension is 0 and otherwise returns max() of the dimensions.
Now that we know length(moves) is n, we know that moves(1,length(moves)) is moves(1,n) which is the scalar that is stored in the last column of the first row. So your vec is a scalar.
for arr = vec
is then looping setting arr to each column of the scalar vec. As vec is a scalar, that is only one column.
If you want to loop over all of the contents of the first row of moves, instead of
vec = moves(1,length(moves))
you should have
vec = moves(1,1:length(moves))
but really that should be
vec = moves(1, 1:size(moves,2))
in case moves has only 1 column.
Now, short-hand for moves(1, 1:size(moves,2)) is moves(1,:) so you can use
vec = moves(1, :);

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by