1

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?

2 Answers 2

4

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);
...
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

If you simply need the index, you can replace the call of ismember for MemberInd = find(vector==i);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.