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