MATLAB Coder return vector or matrix
1 view (last 30 days)
Show older comments
I have made a simple function to do a calculation and return a matrix. Using MATLAB Coder I intent to use the compiled code in iOS as per the webinar here http://www.mathworks.se/videos/matlab-to-iphone-made-easy-90834.html?form_seq=conf1008&confirmation_page&wfsid=5912317
However, my question is, how do I return the matrix in my Xcode project?
Right now my MATLAB script is called
function A = myFunction()
where A is a 6x6 matrix initialized with zeros for now.
When generating the C code my function will look something like
void myFunction(double A[36])
If, for starters, I just wanted to output the matrix data containing zeros in Xcode, how would I go about this?
What I have tried is to import the compiled .c/.h files, call the initialization i.e.
myFunction_initialize()
Then to get the data, call the function
double A;
myFunction(&A);
NSLog(@"A: %f",A);
However, this returns an error "error: memory read failed for 0x0", so either I have set up something in the wrong way in MATLAB or I am not initializing and/or using it correctly in Xcode, I guess both. I tried to setup my script to return a single value and then it actual sets up a return type in the code. With the matrix however, the return type is void.
Have not been able to find any information, tutorials or examples on the matter, so any help would be much appreciated.
0 Comments
Accepted Answer
Guillaume
on 1 Oct 2014
Edited: Guillaume
on 1 Oct 2014
I've never used Xcode nor matlab coder, but your code looks like C. So I'll reply as if this was C code:
If the signature of myFunction is indeed
void myFunction(double A[36])
then your declaration of A is invalid,
double A;
will only reserve enough memory for one double, not the 36 returned by myfunction. As you pass a pointer to that one double to myfunction, it will attempt to write the other 35 values just after, in uninitialised memory. This will cause all kind of errors (it's a buffer overflow, a major source of vulnerabilities).
You have to declare A the same way as the return value:
double A[36];
As a result, A is now a pointer, so to call myfunction you use:
myfunction(A); //not &A
I don't know anything about NSLog, but it looks like a printf substitute with a weird @ syntax. In which case, if you want to print the content of A, you'll have to use a loop:
for (int idx = 0; idx < 36; ++idx)
NSLog(@"A[%d]: %f", idx, A[idx]);
More Answers (0)
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!