Matlab实现支持代码生成的栈和队列数据结构
matlab没有内置的队列和栈数据结构,本文介绍一种使用Matlba函数和coder.varsize实现存储结构体的队列和栈方法,支持代码生成转成C语言或mex。%CREATEVT 预创建结构体,方便代码生成% 此处显示详细说明vt=struct;vt.x=0;vt.y=0;vt.z=0;end。
·
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
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)