Initiating a For Loop!

3 visualizzazioni (ultimi 30 giorni)
GoodVibesVeal
GoodVibesVeal il 9 Ott 2016
Risposto: Walter Roberson il 9 Ott 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!!!

Risposta accettata

Walter Roberson
Walter Roberson il 9 Ott 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, :);

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by