Matlab实现支持代码生成的栈和队列数据结构

1.前言

matlab没有内置的队列和栈数据结构,本文介绍一种使用Matlba函数和coder.varsize实现存储结构体的队列和栈方法,支持代码生成转成C语言或mex。设要存储的结构体由如下函数创建:

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

2.实现队列

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

使用示例:

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.实现栈

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

栈使用示例:

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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安布奇

喜欢的朋友给点支持和鼓励吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值