Simple mex question: how to call a mex function in matlab utilizing variables defined in matlab
조회 수: 14 (최근 30일)
이전 댓글 표시
So I'm trying to convert pieces of a matlab program into mex files to increase the execution speed. The program has about 20 different matlab scripts in it. I'm relatively new to both c and matlab, how do I integrate the mex files into matlab? As an example, how do I rewrite this struct from .m to c to compile as mex to be used in the program?
function [local] = LocalInfo(Euler, k, q, qh, forcing)
% Extract local info for element k
% local struct
local = [];
local.force = feval(forcing, Euler, Euler.x(:,k));
local.q = squeeze(q(:,k,:));
local.q0 = squeeze(Euler.q0(:,k,:));
local.nx = Euler.nx(:,k);% normal vector
local.J = Euler.J(1,k);
local.rx = Euler.rx(1,k);
local.qh = reshape(qh(k:k+1,:),[],1);
local.k = k;
Thanks in advance
댓글 수: 0
채택된 답변
Fred Smith
2014년 7월 14일
MEX-functions can be called from MATLAB by name like any other MATLAB function. If you have foo.mexw64, you call it using regular function syntax from within MATLAB: foo(3,4). If both foo.m and foo.mexw64 exist, then foo(3,4) in MATLAB will invoke foo.mexw64 preferentially. This simple mechanism can be used to replace a MATLAB function with a MEX-function.
MEX functions can be created by hand from C or FORTRAN code using the "MEX" command. Your C or FORTRAN code will have to conform the the MEX-function API.
Alternatively, you can use MATLAB Coder to automatically convert your MATLAB code into C code, and wrap it up as a MEX-function. MATLAB Coder can handle many, but not all MATLAB constructs. The amount of acceleration you get will heavily depend on your application.
댓글 수: 0
추가 답변 (2개)
Jan
2014년 7월 15일
This piece of code is processed efficiently in Matlab. If you call a mex-function, which calls Matlab again for the feval, a lot of time is spend in the overheads of the interfaces. Therefore I'm convinced that this piece of code is faster, when you leave it in Matlab.
댓글 수: 0
Mukul Rao
2014년 7월 14일
Hi,
MEX files are used to run C/C++ or Fortran codes in the MATLAB environment. This means that if you have an existing C code that you would like to execute in the MATLAB environment, you would have to first convert it to a MEX file by making certain changes, described in detail in the links below:
I assume that you have a few MATLAB scripts that you would like to run as a C application? In that case what would work best for you is the MATLAB Compiler toolbox. MATLAB Compiler can convert MATLAB code into a standalone executable or C/C++ shared libraries. Please refer the following link to get introduced to the MATLAB compiler:
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Troubleshooting in MATLAB Compiler SDK에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!