[英]Using custom C structures with MATLAB coder
我需要幫助在 MATLAB 中初始化和使用自定義 C 結構。 我的目標是利用外部 C 結構和函數編寫 MATLAB 代碼。 使用這些 C 結構生成的 MATLAB 代碼將由 Z8F6823ABD383A341FBBB 代碼自動轉換為 C。 我正在關注這個示例(請參閱標題為“集成使用自定義數據類型的外部代碼”的部分),但不幸的是,編碼器給了我以下錯誤:
Non-constant expression or empty matrix.
This expression must be constant because its value determines the size or class of some expression.
Error in ==> calc_length_c Line: 23 Column: 35
我相信我的問題在於coder.cstructname
、 struct
和coder.opaque
的錯誤使用。 要使用 MATLAB 編碼器(自動)生成 C 代碼,我使用以下命令:
codegen calc_length_c -args {0.1, 0.2, 0.3, 1.5, 1.7, 1.9} -report vector.c
MATLAB 代碼,文件calc_length_c.m
:
function [l] = calc_length_c(p0x, p0y, p0z, p1x, p1y, p1z) %#coder
%CALC_LENGTH Calculates vector length
% Calculates vector length. Vector is given by two points in Cartesian 3D space.
% include statements
coder.cinclude('vector.h');
% declare custom C datatypes
coder.cstructname(p0, 'point', 'extern', 'HeaderFile', 'vector.h');
coder.cstructname(p1, 'point', 'extern', 'HeaderFile', 'vector.h');
coder.cstructname(v, 'vector', 'extern', 'HeaderFile', 'vector.h');
% initialise points
p0 = struct('x', 0.0, 'y', 0.0, 'z', 0.0);
p1 = struct('x', 0.0, 'y', 0.0, 'z', 0.0);
v = struct('p0', p0, 'p1', p1);
% initialise points
p0 = coder.ceval('create_point', p0x, p0y, p0z);
p1 = coder.ceval('create_point', p1x, p1y, p1z);
% initialise vector
v = coder.opaque('create_vector', p0, p1); % <- error occurs here!
% calculate vector length
l = 0.0;
l = coder.opaque('calc_length', v);
end
C 代碼,文件vector.c
:
#include <math.h>
#include "vector.h"
// Creates point in 3D Cartesian space
struct point create_point(double x, double y, double z) {
struct point p;
p.x = x;
p.y = y;
p.z = z;
return p;
}
// Creates vector in 3D Cartesian space, defines origin and end points
struct vector create_vector(struct point p0, struct point p1) {
struct vector v;
v.p0 = p0;
v.p1 = p1;
return v;
}
// Calculates length of vector in 3D Cartesian space
double calc_length(struct vector v) {
return sqrt( pow(v.p1.x-v.p0.x, 2.0) +
pow(v.p1.y-v.p0.y, 2.0) +
pow(v.p1.z-v.p0.z, 2.0) );
}
C 代碼,文件vector.h
:
// Definition of point in 3D Cartesian space
struct point {
double x;
double y;
double z;
};
// Definition of vector in 3D Cartesian space
struct vector {
struct point p0;
struct point p1;
};
// Routine signatures
struct point create_point(double x, double y, double z);
struct vector create_vector(struct point p0, struct point p1);
double calc_length(struct vector u);
如果create_vector
是 function,你想用coder.ceval
來調用它。 function coder.opaque
可以被認為僅用於類型聲明。
根據您的代碼,您已經將v
預初始化為結構並在其上使用了coder.cstructname
。 因此,只需將coder.opaque
切換為coder.ceval
,您就應該開始營業了。 后面對calc_length
的引用也是如此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.