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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top