mex2 Inputs and Outputs

本文介绍了一种用于矩阵列归一化的C语言实现方法,并提供了相应的MATLAB mex函数及调用示例。该方法通过计算每列的p范数并进行归一化处理,确保归一化后的矩阵每一列的p范数等于1。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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, 输入



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值