15

Can I have a stack data structure in matlab?

For example a stack of integers where I can push elements in it like stack.push(i), get elements out of it like i = stack.pop() and check out if it is empty stack.isempty().

Simon
  • 4,999
  • 21
  • 69
  • 97
  • MATLAB has 'full' OOP capabilities. Just write your stack class. See documentation for MATLAB OOP: http://www.mathworks.com/help/techdoc/matlab_oop/ug_intropage.html – zellus Nov 12 '10 at 11:06

5 Answers5

19

I do not think MATLAB has one even in the newer versions. But you can use Java, it is a "first class citizen" in MATLAB, it would work perfectly with integers as you need it. See also queue and linked-list related questions.

Just write in MATLAB stack=java.util.Stack() and then you can call methods on it as in your question stack.push(i), ecc.

Community
  • 1
  • 1
Mikhail Poda
  • 5,742
  • 3
  • 39
  • 52
5

You can roll your own or you can use someone else's, like this.

A very simple homemade stack would be an array with a count, the count pointing to the topmost item.

Skurmedel
  • 21,515
  • 5
  • 53
  • 66
1

I have used the Java one in MATLAB and honestly it is very slow. It's much better to do what @skurmedel said, like so:

Ptr = 1;
Stack(ptr,:) = [x,y];
Ptr = ptr + 1;

And to simulate pop:

A = stack(ptr,1);
B = stack(ptr,2);
Ptr = ptr - 1;
Max von Hippel
  • 2,856
  • 3
  • 29
  • 46
Farouk
  • 154
  • 5
0

There is a useful submission in FileExchange:

yuk
  • 19,098
  • 13
  • 68
  • 99
0

Please use MATLAB arrays as is. They are 100 times faster than using any java util. Write the extra logic to make the array work like a stack.

From personal experience just try to re-write your algorithm to use MATLAB array.

AGD
  • 34
  • 3