⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mexfunction.cpp

📁 matlab混合编程(书中程序) 第四章
💻 CPP
字号:
// MexFunction.cpp : Defines the entry point for the DLL application.

#include "stdafx.h"
#include "MexFunction.h"

#include "Matlab.h"

#pragma comment(lib, "libmx.lib")
#pragma comment(lib, "libmat.lib")
#pragma comment(lib, "libmex.lib")
#pragma comment(lib, "libmatlb.lib")

void ComputePrimes(double* y, int n);
BOOL IsPrime(int n);

BOOL APIENTRY DllMain( HANDLE hModule, 
                       DWORD  ul_reason_for_call, 
                       LPVOID lpReserved
					 )
{
    switch (ul_reason_for_call)
	{
		case DLL_PROCESS_ATTACH:
		case DLL_THREAD_ATTACH:
		case DLL_THREAD_DETACH:
		case DLL_PROCESS_DETACH:
			break;
    }
    return TRUE;
}


void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
	if (nrhs != 1) 
	{
		mexErrMsgTxt("One input required.");
	} 
	else if (nlhs > 1) 
	{
		mexErrMsgTxt("Too many output arguments");
	}	
	
	/* The input must be a noncomplex scalar integer.*/
	int mrows, ncols;
	mrows = mxGetM(prhs[0]);
	ncols = mxGetN(prhs[0]);
	
	if (!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || 
		!(mrows == 1 && ncols == 1)) 
	{
		mexErrMsgTxt("Input must be a noncomplex scalar integer.");
	}
	
	double x, *y;
	
	x = mxGetScalar(prhs[0]);
	
	/* Create matrix for the return argument. */
	plhs[0] = mxCreateDoubleMatrix(mrows /* 1 */, (int) x, mxREAL);
	
	y = mxGetPr(plhs[0]);
	
	//call ComputePrimes subroutines to fill vector of primes
	ComputePrimes(y, (int) x);	
}

void ComputePrimes(double* y, int n)
{
	int index=0, i=2;
	
	
	while (index!=n)
	{
		if (IsPrime(i))
		{
			y[index]=i;
			index++;
		}
		
		i++;
	}
}

//return TRUE if n is a prime number
BOOL IsPrime(int n)
{
	for (int i=2; i<=n/2; i++)
	{
		if (n%i==0)
			return FALSE;
	}
	
	return TRUE;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -