How to Loop in mexfunction?
Show older comments
Hello,
I am working on 2d array in mexfunction. And I have a couple of questions about it.
This is the example that I modify a code that I found on the website.
/*==========================================================
* arrayMultiplier.c
*
* Multiplies a 1xN matrix with a N X N matrix
* and outputs a 1xN matrix
*
* The calling syntax is:
* outMatrix = arrayProduct(vector, array)
*========================================================*/
#include "mex.h"
/* The computational routine */
void arrayMultiplier( double *vec, double *arr, int n, int temp ,double *z){
temp = temp + 1;
for (int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
z[i] += vec[j] * arr[j+i*n];
}
}
}
/* The gateway function */
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[]) {
double *vec;
double *arr;
int nr;
double *outMatrix;
int tempr;
vec = mxGetPr(prhs[0]);
arr = mxGetPr(prhs[1]); /* This is where the warning appears */
nr = mxGetScalar(prhs[2]); /*The "n" parameter of the 1 x n output matrix*/
tempr = mxGetScalar(prhs[3]);
/* creating the output matrix */
plhs[0] = mxCreateDoubleMatrix(1,nr,mxREAL);
/* get a pointer to the real data in the output matrix */
outMatrix = mxGetPr(plhs[0]);
/* call the computational routine */
arrayMultiplier(vec,arr,nr,tempr,outMatrix);
}
After this I made .m file
clear all;
clc;
tic
cd 'C:\Users\chang\Desktop\New Folder'
mex testing.c
% ================ 1. Parameters and Constants ============================
numb = 1
A = [1,2,3,4];
B = [1,2,3,4;5,6,7,8;1,2,3,4;5,6,7,8];
AAA = testing(A, B, 4, numb);
I thought by running this code, I should get numb = 2 becasue I added temp = temp +1 in the .c file
Then I got right answer for A*B but numb is still 1 which is quite different from what I expected.
This is quite a simple version of what I am trying to do.
I am trying to use 'while' in the code but everytime I run the code it just run one time and never repeat.
while (it <= itmax) {
it = it ++;
Then I found out that 'temp = temp + 1' doesn't work as what I expected.
Any solutions?
Thanks in advance.
P.S
Is there a way to have matrix multiplication inside mex function?
So that I can just just have A = matrixMultiply(B,C) instead of using for loop to get A.
Accepted Answer
More Answers (0)
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) 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!