1. 新建normalizecolsmx.c文件
/* normalizecolsmx.c Normalize the columns of a matrix
Syntax: B = normalizecols(A)
or B = normalizecols(A,p)
The columns of matrix A are normalized so that norm(B(:,n),p) = 1. */
#include <math.h>
#include "mex.h"
#define IS_REAL_2D_FULL_DOUBLE(P) (!mxIsComplex(P) && mxGetNumberOfDimensions(P) == 2 && !mxIsSparse(P) && mxIsDouble(P))
#define IS_REAL_SCALAR(R) (IS_REAL_2D_FULL_DOUBLE(P) && mxGetNumberOfElements(P) == 1)
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
#define B_OUT plhs[0]
#define A_IN prhs[0]
#define P_IN prhs[1]
double *B, *A, p, colnorm;
int M, N, m, n;
if( nrhs < 1 || nrhs > 2)
mexErrMsgTxt("Wrong number of input arguments.");
else if(nlhs > 1)
mexErrMsgTxt("Too many output arguements");
if( !IS_REAL_2D_FULL_DOUBLE(A_IN) )
mexErrMsgTxt("A must be a real 2D full double array.");
if( nrhs == 1)
p = 2.0;
else
p = mxGetScalar(P_IN);
M = mxGetM(A_IN);
N = mxGetN(A_IN);
A = mxGetPr(A_IN);
B_OUT = mxCreateDoubleMatrix(M, N, mxREAL);
B = mxGetPr(B_OUT);
for(n = 0; n < N; n++)
{
for(m = 0, colnorm = 0.0; m < M; m++)
colnorm += pow(A[m + M*n], p);
colnorm = pow( fabs(colnorm), 1.0/p);
for(m = 0; m < M; m++)
B[m + M * n] = A[m + M * n]/colnorm;
}
return ;
}
2. 编译normalizecolsmx.c 文件
mex normalizecolsmx.c
3. 新建normalizecols.m文件,在此文件使用c文件编译出来的mexw64文件
%normalizecols.m
function B = normalizecols(A, p)
if nargin < 2
if nargin < 1
error('Not enough input arguements');
end
p = 2;
end
if ~isreal(A) || ndims(A) ~= 2 || issparse(A) || ~isa(A, 'double')
error('A must be a real 2D full double array.');
elseif ~ isreal(p) || ~isa(p, 'double') || numel(p) ~= 1
error('P must be a real double scalar.');
end
B = normalizecolsmx(A, p);
end
4. 在命令行中使用normalizecols.m, 输入