How to loop on vector values and have indices too

In summary, a vector is a data structure in programming used to store a collection of values in a sequential manner. To loop through a vector, you can use a for loop and access individual values using the index of the vector. You can also use a counter variable or built-in functions to get the index of a specific value while looping. Having indices while looping allows for specific operations and easy modification or deletion of values. While loops can also be used to iterate through a vector, but require manual incrementing and conditions to end the loop.
  • #1
funyhony
9
0
i want to loop on K vector values
K = [3 5 7 9 11]

and have with me inside the loop the index of the current vector value

if i made
for K = [3 5 7 9 11]
disp(K)
end

i'll not have the index of K values

i mean when K=9 i want to know that I'm in index 4

how to make that??
 
Physics news on Phys.org
  • #2
What language are you looking to do this in? If this is MATLAB, your output would actually display the index value (K) with every iteration of the loop. Given how quickly this would execute, you'll probably just see 3, 5, 7, 9, 11 printed on successive lines.
 

FAQ: How to loop on vector values and have indices too

What is a vector?

A vector is a data structure in programming that stores a collection of values, typically of the same data type, in a sequential manner.

How do I loop through a vector in programming?

In most programming languages, you can use a for loop to iterate through a vector. The loop will run for the length of the vector and you can access the individual values using the index of the vector.

How do I get the index of a vector value while looping?

You can use a counter variable in your for loop to keep track of the index as you loop through the vector. Alternatively, many programming languages have built-in functions that return the index of a specific value in a vector.

What is the benefit of having indices while looping through a vector?

Having access to the indices of a vector allows you to perform specific operations on individual elements or groups of elements within the vector. It also allows you to easily modify or delete specific values within the vector.

Can I use a while loop to iterate through a vector?

Yes, you can use a while loop to iterate through a vector, but you will need to manually increment the counter variable and add conditions to end the loop once you reach the end of the vector.

Similar threads

Replies
2
Views
1K
Replies
10
Views
3K
Replies
10
Views
4K
Replies
10
Views
2K
Replies
6
Views
3K
Back
Top