Search code examples
matlabvectorliterate-programming

How to iterate over a changing vector in Matlab, not consecutive number?


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


Solution

  • 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."