edgarmtze
edgarmtze

Reputation: 25038

for loop in matlab

How do you get every index of a vector inside a loop, this is to pass a function the values of vector

vector =[ 20 , 30 , 60 ,45 ,26 ,17 ,28,9, 10,3 ]


n = 10
for i=1:n
    somefunt( vector(i) );
end

So this is translated

 somefunt( vector(20) );
 somefunt( vector(30) );
 somefunt( vector(60) );
 ...

How to do this?

Upvotes: 1

Views: 390

Answers (2)

Dawn
Dawn

Reputation: 3628

In addition to what @gnovice wrote, if you want the index of the vector element you can use the ismember function:

vector =[ 20 , 30 , 60 ,45 ,26 ,17 ,28,9, 10,3 ]
for i = vector
    [TempFlag, MemberInd] = ismember( i, vector );

    fprintf('vector(%d) is %d\n', MemberInd, i);
    % somefunt( i );
end

Upvotes: 1

gnovice
gnovice

Reputation: 125854

If you want to pass all the values in vector to your function somefunt in a for loop, you can just use vector as your loop values like so:

for i = vector
  somefunt(i);
end

This will be equivalent to:

somefunt(20);
somefunt(30);
somefunt(60);
...

Upvotes: 4

Related Questions