function that adds element to queue in matlab

Here's an example of a MATLAB function that adds an element to a queue:

main.m
function queue = enqueue(queue, element)
% Add an element to the end of the queue
queue(end+1) = element;
end
110 chars
5 lines

In this function, the first argument is the current queue, and the second argument is the element to be added. We simply append the new element to the end of the queue using MATLAB's indexing notation end+1, which adds one element to the end of the vector. The modified queue is returned as the output of the function. You can call this function as follows:

main.m
q = [];  % initialize an empty queue
q = enqueue(q, 42);  % add the number 42 to the queue
91 chars
3 lines

After this code is executed, the queue q will contain a single element, 42.

gistlibby LogSnag