How to find the index of the first and last non-zero value of a vector ?
32 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Adnan Hayat
am 14 Dez. 2020
Bearbeitet: Adnan Hayat
am 15 Dez. 2020
Hello, I have a vector suppose a function f(x), such that
f(x)= ...0,0,0,0,0,0,0,0,5,6,7,4,3,5,6,7,8,0,0,0,0,0,0,0... and
x = 1,2,3,4,5,....
I don't know which command can I use to find those values of x for which the values of f(x) are 5 and 8 (i.e the first and last non-zero values)?
0 Kommentare
Akzeptierte Antwort
Daniel Pollard
am 14 Dez. 2020
Bearbeitet: Daniel Pollard
am 14 Dez. 2020
f = ...0,0,0,0,0,0,0,0,5,6,7,4,3,5,6,7,8,0,0,0,0,0,0,0...;
x_idx = find(f);
x = [x_idx(1), x_idx(end)];
where x is the positions of the first non-zero component and the last non-zero component.
Edit To correct a mis-type.
7 Kommentare
Rik
am 14 Dez. 2020
Note that f_x=f(x);ind=[find(f_x,1,'first') find(f_x,1,'last')]; might be faster, as the JIT might be able to optimize this call.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!