How can I find the starting index number when my numbers are changing through a column vector?
3 views (last 30 days)
Show older comments
How can I find the starting index number when my numbers are changing through a column vector?
2 Comments
Answers (2)
Star Strider
on 6 Oct 2015
Edited: Star Strider
on 6 Oct 2015
If none of the values in your vector are zero, the first index is the first non-zero value. MATLAB will create a vector with defined indices, filling the previous entries with zero:
V(4:7) = randi(9, 1, 4)
V =
0 0 0 5 8 4 2
Use the find function to return the first non-zero entry:
first_nonzero_index = find(V > 0, 1, 'first')
first_nonzero_index =
4
EDIT — To find the start and end of a sequence, this works:
V = [1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 4 4 4 4 4 5 5 5 6 6 6 6 6 6];
first_idx = find(V == 2, 1, 'first'); % Start Of ‘2’ Repeats
last_idx = find(V == 2, 1, 'last'); % End Of ‘2’ Repeats
first_idx =
6
last_idx =
13
0 Comments
Thorsten
on 6 Oct 2015
Your question is somewhat unclear to me. What do you mean by starting index? If you have a vector in Matlab, the starting index into this vector is always 1.
x = rand(1,100);
x(1) % entry at first index of x
Same for a random permutation of the numbers from 1 to 100;
x = perm(100);
x(1) % entry at first index of x
If you want to find the index where x has the value 1, you can use
idx = find(x == 1);
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!