create a stack in matlab

In MATLAB, we can create a stack using an array or a cell array. Here's how to create a stack using an array:

main.m
% Initializing an empty stack
stack = [];

% Push operation
stack(end+1) = value;

% Pop operation
value = stack(end);
stack(end) = [];
136 chars
10 lines

And here's how to create a stack using a cell array:

main.m
% Initializing an empty stack
stack = {};

% Push operation
stack{end+1} = value;

% Pop operation
value = stack{end};
stack(end) = [];
136 chars
10 lines

In both cases, the end+1 index is used to push an element onto the stack. The end index is used to pop an element from the stack.

gistlibby LogSnag