Change size of input arguments without recompiling mex with codegen
Show older comments
I compiled a simple function with matlab coder. The function takes three input arguments: xvec is [nx,1], yvec is [ny,1] and zmat is [nx,ny]. All is good the first time I run the mex function, but if I subsequently change the size of one of the input arrays (say I change nx from nx=8 to nx=7), the function crashes. Of course I can compile again the code and it runs, but I really want to avoid recompilation every time I change the dimension of the inputs!
MWE here:
clear
clc
close all
nx = 8;
ny = 3;
xvec = linspace(0,1,nx)';
yvec = linspace(0,1,ny)';
zmat = xvec.^2+yvec'; % [nx,ny]
%size(zmat)
disp('Calling myfun...')
res = myfun(xvec,yvec,zmat);
% MEX with codegen
disp('Compiling MEX...')
cfg = coder.config('mex');
cfg.GenerateReport = true;
codegen -config cfg myfun -args {xvec,yvec,zmat} -o myfun_mex
disp('Calling myfun_mex...')
res_mex = myfun_mex(xvec,yvec,zmat);
err_mex = abs(res-res_mex)
and here is the function:
function res = myfun(x,y,z)
res = sum(x)+sum(y)+sum(sum(z));
end
First time, I compile and it runs OK. Then, if I set nx=7, it crashes with the following error message:
```
Incorrect size for expression 'x': expected [8x1] but found [7x1].
Error in myfun_mex
Error in main (line 22)
res_mex = myfun_mex(xvec,yvec,zmat);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
Any help is greatly appreciated, thanks!
Accepted Answer
More Answers (1)
Walter Roberson
on 26 Jan 2025
0 votes
You might need to define a maximum array size.
1 Comment
Alessandro
on 26 Jan 2025
Edited: Alessandro
on 26 Jan 2025
Categories
Find more on Algorithm Design Basics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!