How to iterate over a changing vector in Matlab, not consecutive number?
-
25-07-2021 - |
Вопрос
I am really a beginner level at matlab. Now I want to have a loop, such that it iterates over a vector (not consecutive numbers) which contains a decreasing number of elements through iteration.
For example, I have [1; 2 ;3; 4]
(thinking of it as person 1, 2, 3, 4)
then I want to do something such that for example person 1 and 4 gets food, person 2 and 3 left with no food.
In the next round, I want person 2 and 3 (those unassigned)to go through the assignment process again but not 1 and 4. So I create a vector [2;3] to keep track of those left without food.
However,the for i=1:length(vector)
gives me a series of consecutive numbers, what I want is
for i in vector do something; end
How to implement this?
when I just put
i=vector,
Matlab says Index exceeds matrix dimensions
Решение
If you want to loop through an arbitrary vector, just use that vector directly in a for loop. For example:
vector = [3, 4, 7, 1, 1]
for i = vector
disp(i)
end
will output 3 4 7 1 1
. This is the equivalent of "for i in vector do something."
Другие советы
for i=1:length(vector)
is giving you an index into the vector - it will always be consecutive because it represents the first..last
position of the vector.
It sounds like you want to get an identifier out of the vector. You can do this within your existing loop: id=vector[i]
Have you thought about using Matlab structs?
s = struct(field1,value1,...,fieldN,valueN)
You can have an array 'people' of structs (of type person) which you can loop through...
for i=1:length(people)
if people(i).HasBeenFeed = False
% feed this person...
end
end