"end-1" as parameter
64 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Chen Lin
am 9 Sep. 2016
Beantwortet: Chen Lin
am 9 Sep. 2016
I have a question on MATLAB Onramp Chapter 5.1 Indexing into Arrays, Task 3:
Under what "real" scenario would I use the "end-1" command to find a value?
In the given example of MATLAB Onramp, the task is to find the value in the 6th row and 3rd column. I understand that I can use the keyword "end" to either find a row or column index to reference of the last element, which is quick and straightforward in a dataset, but why would I use the "end-1" as parameter? Doesn't it make it too complicated to find an "unknown" value?
Any further explanation on this is much appreciated.
2 Kommentare
John D'Errico
am 9 Sep. 2016
It would help if you provide a link. Without that or a copy of the code/question, it is difficult to know what you are talking about.
Akzeptierte Antwort
Guillaume
am 9 Sep. 2016
Well, end-1 is not an unknown location. It's the element before the last. There are plenty of scenarios where you'd want the nth element before the end, so end-n is very useful. e.g.:
- Implementing a LIFO (Last In First Out) stack. When you want to pop the last element from the stack:
function [stack, element] = pop(stack)
element = stack(end); %get last element
stack = stack(1:end-1); %return the stack without the last element
end
- When you want to remove the border around an image:
function croppedimage = cropborder(sourceimage, bordersize)
croppedimage = sourceimage(bordersize+1:end-bordersize, bordersize+1:end-bordersize, :);
end
- split a vector into two:
function [firsthalf, secondhalf] = splitmiddle(vector)
firsthalf = vector(1:ceil(end/2));
secondhalf = vector(ceil(end/2)+1:end);
end
- etc.
0 Kommentare
Weitere Antworten (2)
Steven Lord
am 9 Sep. 2016
Let's say I wanted to add each element of a vector to the next element. I could do this with a for loop, or I could use a vectorized approach. But I can't add the last element of the vector with the next element -- there isn't a next element! So I add every element of the vector EXCEPT the last (which I retrieve using the index vector 1:end-1) to the one just after that (which I retrieve using the index vector (1:end-1)+1 or 2:end.)
x = 1:10;
y = x(1:end-1) + x(2:end);
We introduced in release R2016a a function named movsum that you could use instead to compute y, but the indexing approach works back probably to Cleve's original Fortran version of MATLAB.
0 Kommentare
Communitys
Weitere Antworten in Distance Learning Community
Siehe auch
Kategorien
Mehr zu Downloads 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!