Matlab implements stack and queue data structures that support code generation

1 Introduction

Matlab does not have a built-in queue and stack data structure. This article introduces a queue and stack method that uses Matlba functions and coder.varsize to implement storage structures, and supports code generation into C language or mex. Suppose the structure to be stored is created by the following function:

function vt = createVt()
%CREATEVT 预创建结构体,方便代码生成
%   此处显示详细说明
vt=struct;
vt.x=0;
vt.y=0;
vt.z=0;
end

2. Implement the queue

function y = queue(command, e)
%实现队列数据结构
persistent data;
d=createVt();
if isempty(data)
    data=repmat(d,[1,0]);
end
y = d;
switch (command)
    case {'init'}
        %初始化
        coder.varsize('data');
        d=createVt();
        data=repmat(d,[1,0]);
    case {'dequeue'}
        %出队
        y = data(1);
        data = data(2:size(data, 2));
    case {'enqueue'}
        %入队
        data=[data,e];
    otherwise
        assert(false, ['Wrong command: ', command]);
end
end

Example usage:

function test_queue %#codegen
% The optional directive %#codegen documents that the function
% is intended for code generation.
a=createVt();
queue('init',a);
for i = 30 : 40
    a=createVt();
    a.x=i;
    queue('enqueue', a);
end
for i = 1 : 10
    value = queue('dequeue',a);
    % Display popped value.
    disp(value)
end
end

3. Implement the stack

function y = stack(command, e)
%实现栈数据结构
persistent data;
d=createVt();
if isempty(data)
    data=repmat(d,[1,0]);
end
y = d;
switch (command)
    case {'init'}
        %初始化
        coder.varsize('data');
        d=createVt();
        data=repmat(d,[1,0]);
    case {'pop'}
        %出栈
        y = data(1);
        data = data(2:size(data, 2));
    case {'push'}
        %压栈
        data=[e,data];
    otherwise
        assert(false, ['Wrong command: ', command]);
end
end

Example of stack usage:

function test_stack %#codegen
% The optional directive %#codegen documents that the function
% is intended for code generation.
a=createVt();
stack('init',a);
for i = 1 : 30
    a.x=i;
    stack('push', a);
end
for i = 1 : 10
    value = stack('pop',a);
    % Display popped value.
    disp(value)
end
end

Guess you like

Origin blog.csdn.net/anbuqi/article/details/131696867