Issue with malloc in Mex file - matlab

I have C code which uses FFTW's FFT function. I need to mex the C code, call it and give inputs from matlab and get C performance plots. But ,here the problem is "malloc" fuction used by fftw's functions.
As shown below in method 1, I used FFTW's malloc functions to create input and output array. While in method 2, I used mxMalloc functions (FFTW's malloc functions are not compulsory but recommended to use them, as it will take care of data aligment and which will be helpful for SIMD). With method 1, unable to use parfor. Getting error message as, "All workers are aborted during the execution of parfor loop" and with normal "for" loop method 1 is working fine. Note that, fft function is not called but just IO's are created and deallocated.
Eventhough method 2 is used for allocating memory, FFTW's FFT function uses there functions. 1)fftwf_plan_dft_1d 2)fftwf_execute 3)fftwf_destroy_plan. The function "fftwf_plan_dft_1d" uses malloc as shown here. Because of it I'm unable to use FFTW's FFT function inside parfor.
How to handle this problem? Is there any way to use FFTW ?.
%Method 1
fftwf_complex* inputArray = ffwtf_malloc(1024*sizeof(fftwf_complex));
fftwf_complex* outputArray = ffwtf_malloc(1024*sizeof(fftwf_complex));
//fft_function_call is commented.
fftwf_free(inputArray);
fftwf_free(outputArray);
%Method 2
fftwf_complex* inputArray = mxMalloc(1024*sizeof(fftwf_complex));
fftwf_complex* outputArray = mxMalloc(1024*sizeof(fftwf_complex));
//fft_function_call is commented.
mxFree(inputArray);
mxFree(outputArray);

Related

Can MATLAB Coder generate a function that takes a pointer as input?

I would like to use MATLAB Coder to generate an executable (or a function in an object file) that accepts a pointer to an array as an input.
I used libpointer to create a pointer object and then tried to compile with the following codegen command:
codegen -config:lib foo -args {coder.typeof(pointer_object_name)}
The resulting error message reported that coder.typeof does not support the lipointer type.
My ultimate goal is to create something that can be called from another C function, with no MATLAB in sight, and receive a pointer to an array as an input. Can MATLAB Coder generate something like that?
#ryan-livingston asked for the signature of the function I would like MATLAB Coder to generate.
Suppose that samples is a pointer to an array of floats. I think I want MATLAB Coder to create a void foo(float *samples) that performs various computations on those floats and perhaps writes results to a file or socket.
Now that I have the attention of #ryan-livingston, I suppose I should ask the following.
Can Coder make functions such as resample work with pointers?
Are pointers already being used under the hood, making my concern unnecessary?
If you just generate code with a fixed-size array input, the generated code will be able to accept a pointer. For example:
function x = foo(x)
x = 2*x;
% You can use MATLAB fopen, fprintf, fwrite here to write x to a file
>> codegen foo -args zeros(10,20) -config:lib -report
produces the interface:
void foo(double x[200]);
which is the same as:
void foo(double *x);
because of array to pointer decay on calls in C.
Note that I've used the x = foo(x) syntax to have Coder pass x by reference to foo. Functions declared with the same variable as both input and output generally produce pass by reference when also called with the same variable as input and output at the callsite.

Where is the source code for the function refine(..) used in Matlab's estimateCameraParameters.m?

At line 486 in estimateCameraParameters.m the refine function is called as shown below. Where is the source code of that function ?
I have searched all Matlab scripts but could not find it.
There is no documentation on this function either.
Any idea where to look for it ?
Where is refine hiding ?
errors = refine(stereoParams, imagePoints1(:, :, pairsUsed), ...
imagePoints2(:, :, pairsUsed), shouldComputeErrors);
At line 303 there is a short description of this function :
% refine the initial estimate and compute distortion coefficients using
% non-linear least squares minimization
errors = refine(cameraParams, imagePoints, shouldComputeErrors);
Found it: it's in stereoParameters.m
I just needed to start to step through estimateCameraParameters.m with the debugger.
Additional explanation:
http://se.mathworks.com/help/matlab/matlab_oop/ordinary-methods.html
Either of the following statements is correct syntax for calling a
method where obj is an object of the class defining the compute
method:
obj.compute(inc)
compute(obj,inc)
So refine() is a method not a standalone function.
I did not know that it is possible to call a method on an object using method(object) syntax. This was confusing me and I was thinking that refine() is a standalone method not defined within a class.

Error regarding inlineeval in MATLAB

As part of a group project we have a system of 2 non linear differential equations and we have to draw the S=S(t) , I=I(t) graphic using the midpoint method.
And I'm getting the following error when trying to insert the matrix with the corresponding differential equations:
"Error in inline expression ==> matrix([[-(IS)/1000], [(IS)/1000 - (3*I)/10]])
Undefined function 'matrix' for input arguments of type 'double'.
Error in inline/subsref (line 23)
INLINE_OUT_ = inlineeval(INLINE_INPUTS_, INLINE_OBJ_.inputExpr, INLINE_OBJ_.expr);"
The code I have done is the following:
syms I S
u=[S;I];
F=[-0.001*S*I;0.001*S*I-0.3*I];
F1=inline(char(F),'I','S');
h=100; %Valores aleatórios
T=100000;
ni=(T/h);
u0=[799;1];
f=zeros(1,2);
k=zeros(1,2);
i=1;
while i<=ni
f(1)=F1(u0(1));
f(2)=F1(u0(2));
dx=h*f;
k(1)=F1((u0(1)+h*(1/2)),(u0(2)+h*(1/2)));
k(2)=F1((u0(1)+h*(1/2)),(u0(2)+h*(1/2)));
u1=u0+h*k;
disp('i:'),disp(i)
disp('u= '),disp(u1)
u0=u1;
i=i+1;
end
I'm new to this so the algorithm it's very likely to be wrong but if someone could help me with that error I'd apreciate it. Thank you!
The problem that specifically creates the error is that you are putting two symbolic functions into a matrix and then calling char (which outputs matrix([[-(IS)/1000], [(IS)/1000 - (3*I)/10]]) rather than converting nicely to string).
The secondary problem is that you are trying to pass two functions simultaneously to inline. inline creates a single function from a string (and using anonymous functions instead of inline is preferred anyway). You cannot put multiple functions in it.
You don't need sym here. In fact, avoid it (more trouble than it's worth) if you don't need to manipulate the equations at all. A common method is to create a cell array:
F{1} = #(I,S) -0.001*S*I;
F{2} = #(I,S) 0.001*S*I-0.3*I;
You can then pass in I and S as so:
F{1}(500,500)
Note that both your functions include both I and S, so they are always necessary. Reconsider what you were expecting when passing only one variable like this: f(1)=F1(u0(1));, because that will also give an error.

Problems with Embedded Functions within Simulink

I'm trying to simulate a very simple model using an embedded matlab function that takes the input and add's 10 to the value using a constant block that inputs into the matlab function, which then outputs to a display block.
As soon as I press simulate I get an abundance of errors. First I get a huge paragraph in orange text stating a warning out the solver 'variableStepDiscrete' instead of solver 'ode45'
Here is the remaining lines that are echo'd from the command prompt:
Code Directory :
"/Users/dazgti/Documents/MATLAB/slprj/_sfprj/embeddedFunction/_self/sfun/src"
Machine (#32): "embeddedFunction" Target : "sfun"
Chart "MATLAB Function" (#49):
.
"c2_embeddedFunction.h"
"c2_embeddedFunction.c"
"embeddedFunction_sfun.h"
"embeddedFunction_sfun.c"
"embeddedFunction_sfun_debug_macros.h"
Interface and Support files:
"embeddedFunction_sfun_registry.c"
Code generation failed Attempt to execute SCRIPT union as a function:
/Users/dazgti/Documents/MATLAB/union.m
I have a script file within my matlab directory called union.m, but I have no idea why its mentioning it.
function y = fcn(u)
%#codegen
x = u + 10;
y = x;
MATLAB Function block works by generating "C" code for the MATLAB code you entered in the block. In the process of generating code there could have been a call to union function in MATLAB from MATLAB Function block infrastructure. Since you have overridden the union function instead of the built-in function MATLAB might have attempted to call your script which caused the error. It is better to avoid naming your functions same as MATLAB built-in functions.

How to avoid allocating memory for the returned value each time a function is called

I have a function that returns a large vector and is called multiple times, with some logic going on between calls that makes vectorization not an option.
An example of the function is
function a=f(X,i)
a=zeros(size(X,1),1);
a(:)=X(:,i);
end
and I am doing
for i=1:n a=f(X,i); end
When profiling this (size(X,1)=5.10^5, n=100 ) times are 0.12s for the zeros line and 0.22s for a(:)=X(:,i) the second line. As expected memory is allocated at each call of f in the 'zeros' line.
To get rid of that line and its 0.12s, I thought of allocating the returned value just once, and passing it in as return space each time to an appropriate function g like so:
function a=g(X,i,a)
a(:)=X(:,i);
end
and doing
a=zeros(m,1);
for i=1:n a=g(X,i,a); end
What is surprising to me is that profiling inside g still shows memory being allocated in the same amounts at the a(:)=X(:,i); line, and the time taken is very much like 0.12+0.22s..
1)Is this just "lazy copy on write" because I am writing into a?
2)Going forward, what are the options?
-a global variable for a (messy..)?
-writing a matrix handle class (must I really?)
(The nested function way means some heavy redesigning to make a nesting function to which X is known (the matrix A with notations from that answer)..)
Perhaps this is a bit tangential to your question, but if this is a performance critical application, I think a good way to go is to rewrite your function as a mex file. Here is a quote from http://www.mathworks.com/support/tech-notes/1600/1605.html#intro,
The main reasons to write a MEX-file are:...
Speed; you can rewrite bottleneck computations (like for-loops) as a MEX-file for efficiency.
If you are not familiar with mex files, the link above should get you started. Converting your existing function to C/C++ should not be overly difficult. The yprime.c example included with MATLAB is similar to what you're trying to do, since it is iteratively being called to calculate the derivatives inside ode45, etc.