MATLAB: How to extract last element from the lists

lists

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}

Best Answer

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)