0

Say A=[1,3];. I want to keep chopping the tail of A, except that MALAB does not have a "A.pop()"

I tried to write a code like

for i=m:-1:1;

A=A(1:i-1);  
end

but MATLAB says "Subscript indices must either be real positive integers or logicals."

chappjc
  • 30,359
  • 6
  • 75
  • 132
Suicide Bunny
  • 894
  • 1
  • 10
  • 23
  • You can also index the end of the vector using `end`, as in A = A(1:end-1). – Lazarus Feb 13 '14 at 02:08
  • 1
    Nominally you just want to say A(end) = [ ]; each time through the loop. However note, that particularly for large vectors, this can be a very inefficient thing to do. MATLAB will reallocate memory for the matrix each time through the loop (with the new memory being enough to store one less element than that previous memory), and copy the remaining elements into the new memory, then free the old memory. – Phil Goddard Feb 13 '14 at 02:46
  • Do you need a stack: http://stackoverflow.com/questions/4163920/matlab-stack-data-structure ? – alexandre iolov Feb 13 '14 at 10:41
  • Also see [this question](http://stackoverflow.com/questions/20054047/subscript-indices-must-either-be-real-positive-integers-or-logicals-generic-sol) for a [generic approach](http://stackoverflow.com/a/20054048/983722) to deal with this error. – Dennis Jaheruddin Mar 10 '14 at 10:34

2 Answers2

2

Like this:

if length(A) > 1
    A = A(1:length(A)-1)
else
    A = []
end
CodeMonkey
  • 1,795
  • 3
  • 16
  • 46
1

You can also try this I guess:

if length(A) > 1
    A(end:end) = []
else
    A = []
end
CodeMonkey
  • 1,795
  • 3
  • 16
  • 46