# Taking the last value of a matrix or vector

2.050 visualizzazioni (ultimi 30 giorni)
Villanova il 9 Set 2011
Commentato: Sangbok Lee il 17 Ott 2021
Hi. How can I take a last term of a vector - since my vector dimensions change -, and plug it in somewhere else in my code without keep changing the code?
for example right now I do v(6) to get the 6th term. How can I do it for nth term.... Thanks
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposta accettata

Walter Roberson il 9 Set 2011
v(end)
or
v(length(v))
##### 4 CommentiMostra 2 commenti meno recentiNascondi 2 commenti meno recenti
Marcus il 17 Feb 2019
In MATLAB R2015a, end is faster than length():
>> x = rand(1, 100);
>> tic; for i=1:1e6; y=x(end); clear('y'); end; toc
Elapsed time is 5.475081 seconds.
>> tic; for i=1:1e6; y=x(length(x)); clear('y'); end; toc
Elapsed time is 5.705095 seconds.
Sangbok Lee il 17 Ott 2021
R2021a
I've tried it several times.
"end" is always slightly faster than "length()"
I think "end" works the same way using index numbers.
>> x=rand(10000);
>> tic; for i=1:1e7; y=x(end); clear y; end; toc
Elapsed time is 21.722168 seconds.
>> tic; for i=1:1e7; y=x(length(x),length(x)); clear y; end; toc
Elapsed time is 22.073104 seconds.
>> tic; for i=1:1e7; y=x(10000,10000); clear y; end; toc
Elapsed time is 21.818949 seconds.

Accedi per commentare.

### Categorie

Scopri di più su Logical in Help Center e File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by