How to extract last element from the lists
4 views (last 30 days)
Show older comments
Aswin Sandirakumaran
on 29 Apr 2018
Commented: Walter Roberson
on 30 Apr 2018
Suppose if my List has
list = {[1,2],2,[],[1,2,3]}
eg:
list{1} = [1,2] = %% print last element ==>> 2 list{2} = 2 list{3} = [] list{4} = [1,2,3] ==> 3 new_list = {2,2,[],3}
I need to extract last element from each list{i} Output should be like
new_list = {2,2,0,3}
4 Comments
dpb
on 29 Apr 2018
That's not what the original said; no fair changing the problem and then acting like didn't... :)
Accepted Answer
Walter Roberson
on 29 Apr 2018
Nth = @(L, N) L(N);
PadN = @(L,N) [L,zeros(1,N)];
list = {[1,2],2,[],[1,2,3]};
N = 2;
cellfun(@(L) Nth(PadN(L,N),N), list)
This is what you asked for, the nth element from the lists. But the example output you gave is asking for the last element of the list, not the n'th element.
Last = @(L) L(end);
NonEmpty = @(L) [L,zeros(1,1-length(L))];
cellfun(@(L) Last(NonEmpty(L)), list)
3 Comments
Walter Roberson
on 29 Apr 2018
I need to run some errands for a while; perhaps someone else will have time to explain it.
Walter Roberson
on 30 Apr 2018
You have a list of values in a cell, so it is easiest to run a cellfun() operation to calculate the results.
Now, if you knew ahead of time that the entries were all non-empty then you could just code
cellfun(@(L) L(end), list)
to take the last entry of each of them. But you do have empty entries, and you have defined that those entries should return 0. So we need to detect empty entries and pad them with a 0 before taking the last element of them.
One of the ways to pad with 0 conditionally is to concatenate with zeros(1,1-length(L)) . When the entry is empty then length() is 0 and 1-length() is 1-0 so that becomes zeros(1,1) which is a single 0 concatenated on to the end of the emptiness, leaving a 0. When the entry is not empty then length() is 1 or more and 1-length() is 0 or negative, so that becomes zeros(1,0 or less), which is emptiness concatenated to the end of the non-empty vector, leaving the vector unchanged.
You would be tempted to put those two functionalities together in a single cellfun, like
cellfun(@(L) [L,zeros(1,1-length(L))](end), list) %WRONG
to try to do the concatenation and then take the last element of what results. However, MATLAB does not permit that syntax.
There is an actual function, subsref, that you can call to do indexing. But it is ugly to call and hard to understand. So it is easier to add in an auxillary function such as
Last = @(L) L(end)
and then you can
cellfun(@(L) Last([L,zeros(1,1-length(L))]), list)
The code I posted just broke this into one more level of operation to add a bit of clarity, doing the padding in another auxiliary function.
More Answers (0)
See Also
Categories
Find more on Structures 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!