Matlab - Queue data structure -


i working on implementing queue data structures using cell arrays in matlab. trying write functions advance queue one, search queue specific item. @ moment function looks (car types example data).

function q = createqueue()    q={};   q = enqueue(q,'hilux');   q = enqueue(q,'e-type');   q = enqueue(q,'beetle');   q = enqueue(q,'enzo');   q = enqueue(q,'boxter');   q = dequeue(q)   q = searchqueue(q,'boxter') end  % adds item end of queue. returns new queue. function q = enqueue(q,item)     q{end+1} = item; end   function [q item] = dequeue(q)     q{1} = {};     q{1} = q{2};     q{2} = q{3};     q{3} = q{4};     q{4} = q{5};     q{5} = {}; end  function answer = searchqueue(q, item)     = 1:length(q)         if q{i} == item             answer = fprintf('found @ index %d',i);             break         else             disp('-1')        end     end  end 

currently, dequeue function leaves empty cell, rather removing cell entirely. able avoided? searchqueue function returns error, , lost why. thanks

here's rough first cut @ using matlab's object oriented capabilities. reason creating class reference semantics handle type, allows dequeue/enqueue functions modify cell array directly, removing need reassignment.

i believe code example below answers main question how dequeue without leaving empty cell (could used without oop approach same effect).

to answer question what's wrong search: 1) comparison q{i} == item gives problems because == compares characters (which fails if there string size mismatch) whereas wanted use isequal(); 2) wanted sprintf rather fprintf; , 3) while not strictly wrong, else in loop happens on every item doesn't match, not wanted.

classdef queue < handle                properties         data = {}     end         methods         function q = queue()             % todo: in constructor if desired         end              function item = dequeue(q)             % todo: bounds check             item = q.data(1);             q.data = q.data(2:end);         end          function enqueue(q,item)             q.data{end+1} = item;         end          function answer = search(q, item)             % todo: check multiple occurrences             answer = 'not found';             = 1:length(q.data)                 if isequal(q.data{i},item)                     answer = sprintf('found @ index %d',i);                     break                 end             end         end     end        end 

Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo