文档库 最新最全的文档下载
当前位置:文档库 › matlab接口程序

matlab接口程序

matlab接口程序
matlab接口程序

光盘目录

上篇

第6章

例6.1

第7章

例7.2

例7.3

第8章

例8.1

例8.2

例8.3

下篇

第1章

例1.3

例1.4

例1.5

例1.6

第3章

例3.2

例3.3

第4章

例4.1

例4.2

例4.3

例4.4

例4.5

例4.6

例4.7

例4.8

例4.9

例4.10

例4.11

例4.12

例4.13

例4.14

例4.15

例4.16

第5章

例5.1

例5.2

第6章

例6.4

例6.5

例6.6

例6.7

第7章

例7.2

例7.25

例7.26

例7.27

例7.29

上篇

第6章

例6.1:

collect.m文件:

function collect

y = zeros(1, 100); %Preallocate the matrix

for i = 1:100

y(i) = collect_one;

end

function y = collect_one

persistent t;

if (isempty(t))

t = 0;

end

t = t + 0.05;

y = sin(t);

measure.c文件:

#include "collect_one_external.h"

#include

extern double measure_from_device(void);

void collect_one(int nlhs, mxArray *plhs[],

int nrhs, mxArray *prhs[])

{

plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);

*(mxGetPr(plhs[0])) = measure_from_device();

}

double measure_from_device(void)

{

static double t = 0.0;

t = t + 0.05;

return sin(t);

}

第7章

例7.2:

mrank.m文件:

function r = mrank(n)

r = zeros(n,1);

for k = 1:n

r(k) = rank(magic(k));

end

printmatrix.m文件:

function printmatrix(m)

% Copyright 2004 The MathWorks, Inc.

disp(m);

mrankp.c文件:

/*

* MRANKP.C

* "Posix" C main program

* Calls mlfMrank, obtained by using MCC to compile mrank.m.

*

* $Revision: 1.3.16.2 $

*

*/

#include

#include

#include "libPkg.h"

main( int argc, char **argv )

{

mxArray *N; /* Matrix containing n. */

mxArray *R = NULL; /* Result matrix. */

int n; /* Integer parameter from command line. */

/* Get any command line parameter. */

if (argc >= 2) {

n = atoi(argv[1]);

} else {

n = 12;

}

mclInitializeApplication(NULL,0);

libPkgInitialize();/* Initialize the library of M-Functions */

/* Create a 1-by-1 matrix containing n. */

N = mxCreateScalarDouble(n);

/* Call mlfMrank, the compiled version of mrank.m. */

mlfMrank(1, &R, N);

/* Print the results. */

mlfPrintmatrix(R);

/* Free the matrices allocated during this computation. */

mxDestroyArray(N);

mxDestroyArray(R);

libPkgTerminate(); /* Terminate the library of M-functions */

mclTerminateApplication();

}

例7.3:

multarg.m文件:

function [a,b] = multarg(x,y)

a = (x + y) * pi;

b = svd(svd(a));

multargp.c文件:

#include

#include

#include

#include "libMultpkg.h"

/*

* Function prototype; the MATLAB Compiler creates mlfMultarg

* from multarg.m

*/

void PrintHandler( const char *text )

{

printf(text);

}

int main( ) /* Programmer written coded to call mlfMultarg */ {

#define ROWS 3

#define COLS 3

mclOutputHandlerFcn PrintHandler;

mxArray *a = NULL, *b = NULL, *x, *y;

double x_pr[ROWS * COLS] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

double x_pi[ROWS * COLS] = {9, 2, 3, 4, 5, 6, 7, 8, 1};

double y_pr[ROWS * COLS] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

double y_pi[ROWS * COLS] = {2, 9, 3, 4, 5, 6, 7, 1, 8};

double *a_pr, *a_pi, value_of_scalar_b;

/* Initialize with a print handler to tell mlfPrintMatrix

* how to display its output.

*/

mclInitializeApplication(NULL,0);

libMultpkgInitializeWithHandlers(PrintHandler, PrintHandler);

/* Create input matrix "x" */

x = mxCreateDoubleMatrix(ROWS, COLS, mxCOMPLEX);

memcpy(mxGetPr(x), x_pr, ROWS * COLS * sizeof(double));

memcpy(mxGetPi(x), x_pi, ROWS * COLS * sizeof(double));

/* Create input matrix "y" */

y = mxCreateDoubleMatrix(ROWS, COLS, mxCOMPLEX);

memcpy(mxGetPr(y), y_pr, ROWS * COLS * sizeof(double));

memcpy(mxGetPi(y), y_pi, ROWS * COLS * sizeof(double));

/* Call the mlfMultarg function. */

mlfMultarg(2, &a, &b, x, y);

/* Display the entire contents of output matrix "a". */

mlfPrintmatrix(a);

/* Display the entire contents of output scalar "b". */

mlfPrintmatrix(b);

/* Deallocate temporary matrices. */

mxDestroyArray(a);

mxDestroyArray(b);

libMultpkgTerminate();

mclTerminateApplication();

return(0);

}

第8章

例8.1:

multiplymatrix.m文件:

function m = multiplymatrix(a1, a2)

%MULTIPLYMATRIX Multiplies two matrices

% This function mulitplies the two matrices passed as input. This

% function is used to demonstate the functionality of MATLAB Compiler.

% Refer to the shared library section of MATLAB Compiler for more

% information.

% Copyright 2003 The MathWorks, Inc.

m = a1*a2;

eigmatrix.m文件:

function e = eigmatrix(a1)

%EIGMATRIX Returns the eigen value of the given matrix

% This function returns the eigen value of the input matrix. This

% function is used to demonstate the functionality of MATLAB Compiler.

% Refer to the shared library section of MATLAB Compiler for more

% information.

% Copyright 2003 The MathWorks, Inc.

e = eig(a1);

addmatrix.m文件:

function a = addmatrix(a1, a2)

%ADDMATRIX Add two matrices

% This function adds the two matrices passed as input. This function is

% used to demonstate the functionality of MATLAB Compiler. Refer to the

% shared library section of MATLAB Compiler for more information.

% Copyright 2003 The MathWorks, Inc.

a = a1 + a2;

matrixdriver.c文件:

/*======================================================== *

* MATRIXDRIVER.C Sample driver code that calls the shared

* library created using MA TLAB Compiler. Refer to the

* documentation of MATLAB Compiler for more information on

* this

*

* This is the wrapper C code to call a shared library created

* using MATLAB Compiler.

*

* Copyright 1984-2004 The MathWorks, Inc.

*

*==========================================================*/

#include

/* Include the MCR header file and the library specific header file

* as generated by MATLAB Compiler */

#include "mclmcr.h"

#include "libmatrix.h"

/* This function is used to display a double matrix stored in an mxArray */

void display(const mxArray* in);

int main(){

mxArray *in1, *in2; /* Define input parameters */

mxArray *out = NULL;/* and output parameters to be passed to the library functions */

double data[] = {1,2,3,4,5,6,7,8,9};

/* Call the mclInitializeApplication routine. Make sure that the application

* was initialized properly by checking the return status. This initialization

* has to be done before calling any MATLAB API's or MATLAB Compiler

* generated

* shared library functions. */

if( !mclInitializeApplication(NULL,0) )

{

fprintf(stderr, "Could not initialize the application.\n");

exit(1);

}

/* Create the input data */

in1 = mxCreateDoubleMatrix(3,3,mxREAL);

in2 = mxCreateDoubleMatrix(3,3,mxREAL);

memcpy(mxGetPr(in1), data, 9*sizeof(double));

memcpy(mxGetPr(in2), data, 9*sizeof(double));

/* Call the library intialization routine and make sure that the

* library was initialized properly. */

if (!libmatrixInitialize())

{

fprintf(stderr,"Could not initialize the library.\n");

exit(1);

}

/* Call the library function */

mlfAddmatrix(1, &out, in1, in2);

/* Display the return value of the library function */

printf("The value of added matrix is:\n");

display(out);

/* Destroy the return value since this varaible will be resued in

* the next function call. Since we are going to reuse the variable,

* we have to set it to NULL. Refer to MATLAB Compiler documentation * for more information on this. */

mxDestroyArray(out); out=0;

mlfMultiplymatrix(1, &out, in1, in2);

printf("The value of the multiplied matrix is:\n");

display(out);

mxDestroyArray(out); out=0;

mlfEigmatrix(1, &out, in1);

printf("The Eigen value of the first matrix is:\n");

display(out);

mxDestroyArray(out); out=0;

/* Call the library termination routine */

libmatrixTerminate();

/* Free the memory created */

mxDestroyArray(in1); in1=0;

mxDestroyArray(in2); in2 = 0;

mclTerminateApplication();

return 0;

}

/*DISPLAY This function will display the double matrix stored in an mxArray. * This function assumes that the mxArray passed as input contains double

* array.

*/

void display(const mxArray* in)

{

int i=0, j=0; /* loop index variables */

int r=0, c=0; /* variables to store the row and column length of the matrix */

double *data; /* variable to point to the double data stored within the mxArray */

/* Get the size of the matrix */

r = mxGetM(in);

c = mxGetN(in);

/* Get a pointer to the double data in mxArray */

data = mxGetPr(in);

/* Loop through the data and display the same in matrix format */

for( i = 0; i < c; i++ ){

for( j = 0; j < r; j++){

printf("%4.2f\t",data[j*c+i]);

}

printf("\n");

}

printf("\n");

}

例8.2:

matrixdriver.cpp:

/*============================================================

*

* MATRIXDRIVER.CPP

* Sample driver code that calls a C++ shared library created using

* the MATLAB Compiler. Refer to the MATLAB Compiler documentation

* for more information on this

*

* This is the wrapper CPP code to call a shared library created

* using the MATLAB Compiler.

*

* Copyright 1984-2004 The MathWorks, Inc.

*

*============================================================*/

// Include the library specific header file as generated by the

// MATLAB Compiler

#include "libmatrix.h"

int main(){

// Call application and library initialization. Perform this

// initialization before calling any API functions or

// Compiler-generated libraries.

if (!mclInitializeApplication(NULL,0) ||

!libmatrixInitialize())

{

std::cerr << "could not initialize the library properly" << std::endl;

return -1;

}

try

{

// Create input data

double data[] = {3,6,9,2,4,7,1,5,8};

mwArray in1(3, 3, mxDOUBLE_CLASS, mxREAL);

mwArray in2(3, 3, mxDOUBLE_CLASS, mxREAL);

in1.SetData(data, 9);

in2.SetData(data, 9);

// Create output array

mwArray out;

// Call the library function

addmatrix(1, out, in1, in2);

// Display the return value of the library function

std::cout << "The value of added matrix is:" << std::endl;

std::cout << out << std::endl;

multiplymatrix(1, out, in1, in2);

std::cout << "The value of the multiplied matrix is:" << std::endl;

std::cout << out << std::endl;

eigmatrix(1, out, in1);

std::cout << "The eigenvalues of the first matrix are:" << std::endl;

std::cout << out << std::endl;

}

catch (const mwException& e)

{

std::cerr << e.what() << std::endl;

return -1;

}

catch (...)

{

std::cerr << "Unexpected error thrown" << std::endl;

return -1;

}

// Call the application and library termination routine

libmatrixTerminate();

mclTerminateApplication();

return 0;

}

例8.3

Sierpinski.m:

function [x, y] = sierpinski(iterations, draw)

% SIERPINSKI Calculate (optionally draw) the points in Sierpinski's triangle

% Copyright 2004 The MathWorks, Inc.

% Three points defining a nice wide triangle

points = [0.5 0.9 ; 0.1 0.1 ; 0.9 0.1];

% Select an initial point

current = rand(1, 2);

% Create a figure window

if (draw == true)

f = figure;

hold on;

end

% Pre-allocate space for the results, to improve performance

x = zeros(1,iterations);

y = zeros(1,iterations);

% Iterate

for i = 1:iterations

% Select point at random

index = floor(rand * 3) + 1;

% Calculate midpoint between current point and random point

current(1) = (current(1) + points(index, 1)) / 2;

current(2) = (current(2) + points(index, 2)) / 2;

% Plot that point

if draw, line(current(1),current(2));, end

x(i) = current(1);

y(i) = current(2);

end

if (draw)

drawnow;

end

triangle.c:

/*================================================================= *

* TRIANGLE.C

*

* Calculate the points in Sierpinski's triangle, an elementary

* fractal.

*

* This function calls a

* using MATLAB Compiler.

*

* Copyright 1984-2004 The MathWorks, Inc.

*

*=================================================================*/ #include

/* Include the MCR header file and the library specific header file * as generated by MATLAB Compiler

*/

#include "mclmcr.h"

#include "libtriangle_c.h"

void usage(const char *name)

{

printf("Usage: %s [number of points]\n");

exit (-1);

}

int main(int ac, char *av[])

{

/* Input parameters:

*

* iterations: Number of points to draw in the triangle

* draw: If true, draw the triangle in a figure window before returning.

*/

mxArray *iterations = NULL, *draw = NULL;

/* The Sierpinski function returns the X and Y coordinates of the points * forming the pattern in the triangle.

*/

mxArray *x = NULL, *y = NULL;

/* Default number of iterations */

int num_points = 7500;

/* Validate the number of inputs */

if (ac < 1 || ac > 2)

{

fprintf(stderr, "Expecting 0 or 1 input(s). Found %d\n", ac);

usage(av[0]);

}

/* If we have the right number of inputs (1), try to convert the input * string to an integer.

*/

if (ac == 2)

num_points = atoi(av[1]);

/* Type check on input argument -- atoi() will fail if the input is

* not an integer.

*/

if (num_points == 0)

{

fprintf(stderr, "First argument must be an integer.\n");

usage(av[0]);

}

/* Call the library intialization routine and make sure that the

* library was initialized properly

*/

mclInitializeApplication(NULL,0);

if (!libtriangle_CInitialize())

{

fprintf(stderr,"could not initialize the triangle library

properly\n");

return -1;

}

/* Create the input data */

iterations = mxCreateDoubleScalar(num_points);

draw = mxCreateLogicalScalar(1);

/* Call the library function */

mlfSierpinski(2, &x, &y, iterations, draw);

/* Display the return value of the library function */

printf("Calculated %d points\n", mxGetNumberOfElements(x));

/* Block until user dismisses the figure */

mclWaitForFiguresToDie(NULL);

/* Free the memory used by the return values. */

mxDestroyArray(x); x=NULL;

mxDestroyArray(y); y=NULL;

/* Call the library termination routine */

libtriangle_CTerminate();

/* Free the memory used by the input variables */

mxDestroyArray(iterations); iterations=0;

mxDestroyArray(draw); draw = 0;

/* Shut down all MCR instances */

mclTerminateApplication();

/* Success */

return 0;

}

triangle.cpp(C++源程序)

//=================================================================

//

// TRIANGLE.CPP

// Calculate the points in Sierpinski's triangle, an elementary

// fractal.

//

// This function calls a

// using MATLAB Compiler.

//

// Copyright 2010.2 Yubenran.

//=================================================================*/

// Include the library specific header file

// as generated by MATLAB Compiler

#include "libtriangle.h"

void usage(const char *name)

{

std::cout <<"Usage: %s [number of points]"<< std::endl;

exit (-1);

}

int main(int ac, char *av[])

{

// Call the library intialization routine and make sure that the

// library was initialized properly

if (!mclInitializeApplication(NULL,0)||

!libtriangleInitialize())

{

std::cerr <<"could not initialize the triangle library properly"<< std::endl;

return -1;

}

try

{

// Input parameters:

// iterations: Number of points to draw in the triangle

// draw: If true, draw the triangle in a figure window before returning.

// The Sierpinski function returns the X and Y coordinates of the points

// forming the pattern in the triangle.

mwArray x;

mwArray y;

// Default number of iterations */

int num_points = 7500;

// Validate the number of inputs */

if (ac < 1 || ac > 2)

{

std::cerr <<"Expecting 0 or 1 input(s). Found %d"<< std::endl;

std::cout << ac << std::endl;

usage(av[0]);

}

// If we have the right number of inputs (1), try to convert the input

// string to an integer.

if (ac == 2)

num_points = atoi(av[1]);

// Type check on input argument -- atoi() will fail if the input is

// not an integer.

if (num_points == 0)

{

std::cerr <<"First argument must be an integer."<< std::endl;

usage(av[0]);

}

// Create the input data

mwArray iterations(num_points);

mxLogical l={true};

mwArray draw(l);

// Call the library function */

sierpinski(2, x, y, iterations, draw);

// Display the return value of the library function

std::cout << "Calculated %d points:" << std::endl;

std::cout << num_points << std::endl;

// Block until user dismisses the figure

mclWaitForFiguresToDie(NULL);

}

catch (const mwException& e)

{

std::cerr << e.what() << std::endl;

return -1;

}

catch (...)

{

std::cerr << "Unexpected error thrown" << std::endl;

return -1;

}

// Call the library and application termination routine */

libtriangleTerminate();

mclTerminateApplication();

// Success

return 0;

}

下篇

第1章

例1.3

matcreat.c文件:

/*

* MAT-file creation program

*

* See the MATLAB API Guide for compiling information.

*

* Calling syntax:

*

* matcreat

*

* Create a MAT-file which can be loaded into MATLAB.

*

* This program demonstrates the use of the following functions: *

* matClose

* matGetVariable

* matOpen

* matPutVariable

* matPutVariableAsGlobal

*

* Copyright 1984-2000 The MathWorks, Inc.

* $Revision: 1.13 $

*/

#include

#include /* For strcmp() */

#include /* For EXIT_FAILURE, EXIT_SUCCESS */

#include "mat.h"

#define BUFSIZE 256

int main() {

MATFile *pmat;

mxArray *pa1, *pa2, *pa3;

double data[9] = { 1.0, 4.0, 7.0, 2.0, 5.0, 8.0, 3.0, 6.0, 9.0 }; const char *file = "mattest.mat";

char str[BUFSIZE];

int status;

printf("Creating file %s...\n\n", file);

pmat = matOpen(file, "w");

if (pmat == NULL) {

printf("Error creating file %s\n", file);

printf("(Do you have write permission in this directory?)\n"); return(EXIT_FAILURE);

}

pa1 = mxCreateDoubleMatrix(3,3,mxREAL);

if (pa1 == NULL) {

printf("%s : Out of memory on line %d\n", __FILE__,

__LINE__);

printf("Unable to create mxArray.\n");

return(EXIT_FAILURE);

}

pa2 = mxCreateDoubleMatrix(3,3,mxREAL);

if (pa2 == NULL) {

printf("%s : Out of memory on line %d\n", __FILE__,

__LINE__);

printf("Unable to create mxArray.\n");

return(EXIT_FAILURE);

}

memcpy((void *)(mxGetPr(pa2)), (void *)data, sizeof(data));

pa3 = mxCreateString("MATLAB: the language of technical

computing");

if (pa3 == NULL) {

printf("%s : Out of memory on line %d\n", __FILE__,

__LINE__);

printf("Unable to create string mxArray.\n");

return(EXIT_FAILURE);

}

status = matPutVariable(pmat, "LocalDouble", pa1);

if (status != 0) {

printf("%s : Error using matPutVariable on line %d\n",

__FILE__, __LINE__);

return(EXIT_FAILURE);

}

status = matPutVariableAsGlobal(pmat, "GlobalDouble", pa2);

if (status != 0) {

printf("Error using matPutVariableAsGlobal\n");

return(EXIT_FAILURE);

}

status = matPutVariable(pmat, "LocalString", pa3);

if (status != 0) {

printf("%s : Error using matPutVariable on line %d\n",

__FILE__, __LINE__);

return(EXIT_FAILURE);

}

/*

* Ooops! we need to copy data before writing the array. (Well, * ok, this was really intentional.) This demonstrates that

* matPutVariable will overwrite an existing array in a MAT-file. */

memcpy((void *)(mxGetPr(pa1)), (void *)data, sizeof(data));

status = matPutVariable(pmat, "LocalDouble", pa1);

if (status != 0) {

printf("%s : Error using matPutVariable on line %d\n",

__FILE__, __LINE__);

return(EXIT_FAILURE);

}

/* Clean up. */

mxDestroyArray(pa1);

mxDestroyArray(pa2);

mxDestroyArray(pa3);

if (matClose(pmat) != 0) {

printf("Error closing file %s\n",file);

return(EXIT_FAILURE);

}

/* Re-open file and verify its contents with matGetVariable. */ pmat = matOpen(file, "r");

if (pmat == NULL) {

printf("Error reopening file %s\n", file);

return(EXIT_FAILURE);

}

/* Read in each array we just wrote. */

pa1 = matGetVariable(pmat, "LocalDouble");

if (pa1 == NULL) {

printf("Error reading existing matrix LocalDouble\n");

return(EXIT_FAILURE);

}

if (mxGetNumberOfDimensions(pa1) != 2) {

printf("Error saving matrix: result does not have two

dimensions\n");

return(EXIT_FAILURE);

}

pa2 = matGetVariable(pmat, "GlobalDouble");

if (pa2 == NULL) {

printf("Error reading existing matrix GlobalDouble\n");

return(EXIT_FAILURE);

}

if (!(mxIsFromGlobalWS(pa2))) {

printf("Error saving global matrix: result is not global\n"); return(EXIT_FAILURE);

}

pa3 = matGetVariable(pmat, "LocalString");

if (pa3 == NULL) {

printf("Error reading existing matrix LocalString\n");

return(EXIT_FAILURE);

}

status = mxGetString(pa3, str, sizeof(str));

if(status != 0) {

printf("Not enough space. String is truncated.");

return(EXIT_FAILURE);

}

if (strcmp(str, "MATLAB: the language of technical

computing")) {

几种常见窗函数及其MATLAB程序实现

几种常见窗函数及其MATLAB程序实现 2013-12-16 13:58 2296人阅读评论(0) 收藏举报 分类: Matlab(15) 数字信号处理中通常是取其有限的时间片段进行分析,而不是对无限长的信号进行测量和运算。具体做法是从信号中截取一个时间片段,然后对信号进行傅里叶变换、相关分析等数学处理。信号的截断产生了能量泄漏,而用FFT算法计算频谱又产生了栅栏效应,从原理上讲这两种误差都是不能消除的。在FFT分析中为了减少或消除频谱能量泄漏及栅栏效应,可采用不同的截取函数对信号进行截短,截短函数称为窗函数,简称为窗。 泄漏与窗函数频谱的两侧旁瓣有关,对于窗函数的选用总的原则是,要从保持最大信息和消除旁瓣的综合效果出发来考虑问题,尽可能使窗函数频谱中的主瓣宽度应尽量窄,以获得较陡的过渡带;旁瓣衰减应尽量大,以提高阻带的衰减,但通常都不能同时满足这两个要求。 频谱中的如果两侧瓣的高度趋于零,而使能量相对集中在主瓣,就可以较为接近于真实的频谱。不同的窗函数对信号频谱的影响是不一样的,这主要是因为不同的窗函数,产生泄漏的大小不一样,频率分辨能力也不一样。信号的加窗处理,重要的问题是在于根据信号的性质和研究目的来选用窗函数。图1是几种常用的窗函数的时域和频域波形,其中矩形窗主瓣窄,旁瓣大,频率识别精度最高,幅值识别精度最低,如果仅要求精确读出主瓣频率,而不考虑幅值精度,则可选用矩形窗,例如测量物体的自振频率等;布莱克曼窗主瓣宽,旁瓣小,频率识别精度最低,但幅值识别精度最高;如果分析窄带信号,且有较强的干扰噪声,则应选用旁瓣幅度小的窗函数,如汉宁窗、三角窗等;对于随时间按指数衰减的函数,可采用指数窗来提高信噪比。表1 是几种常用的窗函数的比较。 如果被测信号是随机或者未知的,或者是一般使用者对窗函数不大了解,要求也不是特别高时,可以选择汉宁窗,因为它的泄漏、波动都较小,并且选择性也较高。但在用于校准时选用平顶窗较好,因为它的通带波动非常小,幅度误差也较小。

一个简单的Matlab_GUI编程实例

Matlab GUI编程教程(适用于初学者) 1.首先我们新建一个GUI文件:如下图所示; 选择Blank GUI(Default) 2.进入GUI开发环境以后添加两个编辑文本框,6个静态文本框,和一个按钮,布置如下

图所示; 布置好各控件以后,我们就可以来为这些控件编写程序来实现两数相加的功能了。3.我们先为数据1文本框添加代码; 点击上图所示红色方框,选择edit1_Callback,光标便立刻移到下面这段代码的位置。 1. 2. 3.function edit1_Callback(hObject, eventdata, handles) 4.% hObject handle to edit1 (see GCBO) 5.% eventdata reserved - to be defined in a future version of MATLAB

6.% handles structure with handles and user data (see GUIDATA) 7.% Hints: get(hObject,'String') returns contents of edit1 as text 8.% str2double(get(hObject,'String')) returns contents of edit1 as a double 复制代码 然后在上面这段代码的下面插入如下代码: 1. 2.%以字符串的形式来存储数据文本框1的内容. 如果字符串不是数字,则现实空白内容input = str2num(get(hObject,'String')); %检查输入是否为空. 如果为空,则默认显示为0if (isempty(input)) set(hObject,'String','0')endguidata(hObject, handles); 复制代码 这段代码使得输入被严格限制,我们不能试图输入一个非数字。 4.为edit2_Callback添加同样一段代码 5 现在我们为计算按钮添加代码来实现把数据1和数据2相加的目的。 用3中同样的方法在m文件中找到pushbutton1_Callback代码段 如下; 1.function pushbutton1_Callback(hObject, eventdata, handles) 2.% hObject handle to pushbutton1 (see GCBO) 3.% eventdata reserved - to be defined in a future version of MATLAB 4.% handles structure with handles and user data (see GUIDATA) 复制代码

VB与MATLAB接口的实现

VB与MATLAB接口的实现: https://www.wendangku.net/doc/274757002.html, 实例说明 在本实例中,我们制作一个能够与Matlab进行交互的应用程序。程序运行结果如图78-1所示。 图78-1 运行结果 技术要点 z引用Matlab库 z执行Matlab命令 z结束Matlab 实现过程 ■ 新建项目 打开Visual https://www.wendangku.net/doc/274757002.html,,选择“新建项目”,在项目类型窗口中选择“Visual Basic项目”,在模板窗口中选择“Windows应用程序”,在名称域中输入“CnMatlab”,然后选择保存路径。单击“确认”。 ■ 添加控件 向当前窗体添加五个Button按钮,两个Picture控件,一个Label控件,一个Hscroll控件和一个Vscroll控件。单击菜单“项目|添加引用”,选中“Matlab Automation(Version5.3)Type Library”这一项。 注意:本程序只能在安装有Matlab的机器上运行。 ■ 设置属性 将Label控件和Command按钮的Text属性设置为与界面一致。在此不再赘述。 ■ 添加代码 Dim str1 As String ' 显示正弦图 Private Sub Command1_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Command1.Click Dim matlab As Object matlab = CreateObject("matlab.application") matlab.MinimizeCommandWindow()

MATLABAPI详解

MATLAB、API详解 【例12.1.4-1】有一个绘圆的M脚本文件circle.m如下。希望获得一个MEX绘圆程序。(1)原始的绘圆脚本文件 [circle.m] clf;r=2;t=0:pi/100:2*pi;x=r*exp(i*t); plot(x,'r*');axis('square') (2)对这脚本文件直接编译将因错误而失败 mcc -x circle ??? Error: File "circle" is a Script M-file and cannot be compiled with the current Compiler. Error in ==> H:\MATLAB53\toolbox\compiler\mcc.dll (3)把脚本文件改写成函数文件。 [circle_f.m]: function circle_f(r) clf;t=0:pi/100:2*pi;x=r*exp(i*t); plot(x,'r*');axis('square') (4)再对circle_f.m进行编译,将顺利通过。 mcc -x circle_f %mcc是编译指令,详见12.4节。 (5)运行生成的MEX文件circle_f.dll circle_f(0.5) %调用circle_f绘制一半径为0.5的圆 which circle_f %查询所调用的circle_f的路径全称。

图 12.2.1-1 【Select MATLAB Componets】对话窗的选项局部图 图 12.2.2.1-1 为产生MEX文件所产生的配置屏1

图 12.2.2.1-2 为产生MEX文件所产生的配置屏2 12.1.1.1配置正确性的验证 (1)mex应用程序的验证 cd d:\mywork %把用户目录指定为当前目录 mex my_yprime.c %由my_yprime.c文件生成my_yprime.dll文件my_yprime(1,1:4) %运行my_yprime.dll文件 which my_yprime %获得my_yprime.dll文件的位置信息 ans = 2.0000 8.9685 4.0000 -1.0947 d:\mywork\my_yprime.dll (2)在MATLAB命令窗中验证mcc应用程序 mcc -x my_yprime_m%<1> my_yprime_m(1,1:4) which my_yprime_m ans = 2.0000 8.9685 4.0000 -1.0947 d:\mywork\my_yprime_m.dll (3)在 DOS提示符后验证mex、mcc应用程序

matlab编程实现求解最优解

《现代设计方法》课程 关于黄金分割法和二次插值法的Matlab语言实现在《现代设计方法》的第二章优化设计方法中有关一维搜索的最优化方法的 一节里,我们学习了黄金非分割法和二次插值法。它们都是建立在搜索区间的优先确定基础上实现的。 为了便于方便执行和比较,我将两种方法都写进了一个程序之内,以选择的方式实现执行其中一个。下面以《现代设计方法》课后习题为例。见课本70页,第2—7题。原题如下: 求函数f(x)=3*x^2+6*x+4的最优点,已知单谷区间为[-3,4],一维搜索精度为0.4。 1、先建立函数f(x),f(x)=3*x^2+6*x+4。函数文件保存为:lee.m 源代码为:function y=lee(x) y=3*x^2+6*x+4; 2、程序主代码如下,该函数文件保存为:ll.m clear; a=input('请输入初始点'); b=input('请输入初始步长'); Y1=lee(a);Y2=lee(a+b); if Y1>Y2 %Y1>Y2的情况 k=2; Y3=lee(a+2*b); while Y2>=Y3 %直到满足“大,小,大”为止 k=k+1; Y3=lee(a+k*b); end A=a+b;B=a+k*b; elseif Y1=Y3 %直到满足“大,小,大”为止 k=k+1; Y3=lee(a-k*b); end A=a-k*b;B=a; else A=a;B=a+b; %Y1=Y2的情况 end disp(['初始搜索区间为',num2str([A,B])])%输出符合的区间 xuanze=input('二次插值法输入0,黄金分割法输入1');%选择搜索方式 T=input('选定一维搜索精度'); if xuanze==1 while B-A>T %一维搜索法使精度符合要求 C=A+0.382*(B-A);D=A+0.618*(B-A); %黄金分割法选点

数字信号处理Matlab实现实例(推荐给学生)

数字信号处理Matlab 实现实例 第1章离散时间信号与系统 例1-1 用MATLAB计算序列{-2 0 1 –1 3}和序列{1 2 0 -1}的离散卷积。 解 MATLAB程序如下: a=[-2 0 1 -1 3]; b=[1 2 0 -1]; c=conv(a,b); M=length(c)-1; n=0:1:M; stem(n,c); xlabel('n'); ylabel('幅度'); 图1.1给出了卷积结果的图形,求得的结果存放在数组c中为:{-2 -4 1 3 1 5 1 -3}。 例1-2 用MATLAB计算差分方程 当输入序列为时的输出结果。 解 MATLAB程序如下: N=41; a=[0.8 -0.44 0.36 0.22]; b=[1 0.7 -0.45 -0.6]; x=[1 zeros(1,N-1)];

k=0:1:N-1; y=filter(a,b,x); stem(k,y) xlabel('n');ylabel('幅度') 图 1.2 给出了该差分方程的前41个样点的输出,即该系统的单位脉冲响应。 例1-3 用MATLAB 计算例1-2差分方程 所对应的系统函数的DTFT 。 解 例1-2差分方程所对应的系统函数为: 123 123 0.80.440.360.02()10.70.450.6z z z H z z z z -------++= +-- 其DTFT 为 23230.80.440.360.02()10.70.450.6j j j j j j j e e e H e e e e ωωωω ωωω--------++= +-- 用MATLAB 计算的程序如下: k=256; num=[0.8 -0.44 0.36 0.02]; den=[1 0.7 -0.45 -0.6]; w=0:pi/k:pi; h=freqz(num,den,w); subplot(2,2,1); plot(w/pi,real(h));grid title('实部') xlabel('\omega/\pi');ylabel('幅度')

CA码生成原理及matlab程序实现

作业:用Matlab写C/A码生成器程序,并画生成码的方波图。 C/A码生成原理 C/A 码是用m 序列优选对组合形成的Gold 码。Gold码是由两个长度相同而互相关极大值为最小的m 序列逐位模2 相加所得到的码序列。它是由两个10 级反馈移位寄存器组合产生的,其产生原理如图1 所示。 图1 C/A码生成原理 发生器的抽头号为3和10,发生器的抽头号为2、3、6、8、9、10;发生器的第10位输出的数字即为码,而码是由的两个抽头的输出结果进行模2相加得到。 卫星的PRN码与延时的量是相关联的,对C/A码来说,每颗卫星都有特别的延时,如第1颗GPS卫星的G2 抽为2、6,第2颗为3、7,第3 颗为4、8,第4 颗为5、9 等,如图2所示。通过G2 相位选择可以产生结构不同的伪随机码,从而可以实现不同卫星之间的码分多址技术与卫星识别。

图2 prn序号与G2抽头、时延对应关系 基于MATLAB的GPS信号实现 编写成“codegen”程序,输入[ca_used]=codegen(svnum),其中svnum为卫星号,ca_used 为得到的C/A码序列。程序具体实现流程如下: 在程序中定义一个数组,使得卫星号与G2的码片延时一一对应。 gs2=[5;6;7;8;17;18;139;140;141;251;252;254;255;256;257;258;469;470;471;472;473;474;509;512 ;513;514;515;516;859;860;861;862]; 定义两个1×1 023 的数组g1、g2 用来存放生成的Gold 码。定义一个全1 的10 位数组,作为移位寄存器,相当于G1、G2 生成模块的初值均置为全“1”。按原理式

MATLAB与FPGA的接口

FPGA器件的开发平台与MATLAB接口仿真 2007-09-03 16:24 FPGA器件的开发平台与MATLAB接口仿真 中南财经政法大学信息学院周巍武汉大学电气工程学院张志杰引言 现场可编程逻辑门阵列FPGA器件的出现是超大规模集成电路技术和计算机辅助设计技术发展的结果。FPGA器件集成度高、体积小,具有通过用户编程实现专门应用功能。 它允许电路设计者利用基于计算机的开发平台,经过设计输入、仿真、测试和校验,直到达到预期的结果。目前使用最多的Quartus II 软件支持几乎所有的EDA工具,并且可以通过命令行或Tcl脚本与第三方EDA工具之间进行无缝连接。但在很多工程设计应用中,由FPGA器件完成的主程序中只完成大量的数学运算,程序调试时以二进制输出的信号可视性差,给设计人员进行仿真、调试带来了很多不便。对于很多工程设计人员来说MATLAB是一种熟悉的具有强大的运算功能和波形仿真、分析功能的软件,如果能将FPGA与MA TLAB接口,就可以快速、准确、直观地对FPGA程序进行校验和仿真,尤其在波形信号处理等工程应用领域具有实际意义。 Quartus II 开发软件 Altera公司的QuartusII软件提供了可编程片上系统(SOPC)设计的一个综合开发环境。Quartus II 开发工具人机界面友好、易于使用、性能优良,并自带编译、仿真功能。QuartusII 软件支持VHDL和Verilog硬件描述语言的设计输入、基于图形的设计输入方式以及集成系统级设计工具。QuartusII软件可以将设计、综合、布局和布线以及系统的验证全部都整合到一个无缝的环境之中,其中也包括和第三方EDA工具的接口。QuartusII设计软件根据设计者需要提供了一个完整的多平台开发环境,它包含整个FPGA和CPLD设计阶段的解决方案。图1说明了QuartusII软件的开发流程。 在实际应用设计中,对程序原理性及可执行性的验证主要集中在程序修改阶段,尤其在

基于matlab程序实现人脸识别

基于m a t l a b程序实现 人脸识别 TYYGROUP system office room 【TYYUA16H-TYY-TYYYUA8Q8-

基于m a t l a b程序实现人脸识别 1.人脸识别流程 基于YCbCr颜色空间的肤色模型进行肤色分割。在YCbCr色彩空间内对肤色进行了建模发现,肤色聚类区域在Cb—Cr子平面上的投影将缩减,与中心区域显着不同。采用这种方法的图像分割已经能够较为精确的将人脸和非人脸分割开来。 人脸识别流程图 2.人脸识别程序 (1)人脸和非人脸区域分割程序 function result = skin(Y,Cb,Cr) %SKIN Summary of this function goes here % Detailed explanation goes here a=; b=; ecx=; ecy=; sita=; cx=; cy=; xishu=[cos(sita) sin(sita);-sin(sita) cos(sita)]; %如果亮度大于230,则将长短轴同时扩大为原来的倍 if(Y>230) a=*a; b=*b; end %根据公式进行计算 Cb=double(Cb); Cr=double(Cr);

t=[(Cb-cx);(Cr-cy)]; temp=xishu*t; value=(temp(1)-ecx)^2/a^2+(temp(2)-ecy)^2/b^2; %大于1则不是肤色,返回0;否则为肤色,返回1 if value>1 result=0; else result=1; end end (2)人脸的确认程序 function eye = findeye(bImage,x,y,w,h) %FINDEYE Summary of this function goes here % Detailed explanation goes here part=zeros(h,w); %二值化 for i=y:(y+h) for j=x:(x+w) if bImage(i,j)==0 part(i-y+1,j-x+1)=255; else part(i-y+1,j-x+1)=0; end end end [L,num]=bwlabel(part,8); %如果区域中有两个以上的矩形则认为有眼睛 if num<2 eye=0;

matlab源代码实例

1.硬币模拟试验 源代码: clear; clc; head_count=0; p1_hist= [0]; p2_hist= [0]; n = 1000; p1 = 0.3; p2=0.03; head = figure(1); rand('seed',sum(100*clock)); fori = 1:n tmp = rand(1); if(tmp<= p1) head_count = head_count + 1; end p1_hist (i) = head_count /i; end figure(head); subplot(2,1,1); plot(p1_hist); grid on; hold on; xlabel('重复试验次数'); ylabel('正面向上的比率'); title('p=0.3试验次数N与正面向上比率的函数图'); head_count=0; fori = 1:n tmp = rand(1); if(tmp<= p2) head_count = head_count + 1; end p2_hist (i) = head_count /i; end figure(head); subplot(2,1,2); plot(p2_hist); grid on; hold on; xlabel('重复试验次数'); ylabel('正面向上的比率'); title('p=0.03试验次数N与正面向上比率的函数图'); 实验结果:

2.不同次数的随机试验均值方差比较 源代码: clear ; clc; close; rand('seed',sum(100*clock)); Titles = ['n=5时' 'n=20时' 'n=25时' 'n=50时' 'n=100时']; Titlestr = cellstr(Titles); X_n_bar=[0]; %the samples of the X_n_bar X_n=[0]; %the samples of X_n N=[5,10,25,50,100]; j=1; num_X_n = 100; num_X_n_bar = 100; h_X_n_bar = figure(1);

遗传算法的原理及MATLAB程序实现

遗传算法的原理及MATLAB程序实现 1 遗传算法的原理 1.1 遗传算法的基本思想 遗传算法(genetic algorithms,GA)是一种基于自然选择和基因遗传学原理,借鉴了生物进化优胜劣汰的自然选择机理和生物界繁衍进化的基因重组、突变的遗传机制的全局自适应概率搜索算法。 遗传算法是从一组随机产生的初始解(种群)开始,这个种群由经过基因编码的一定数量的个体组成,每个个体实际上是染色体带有特征的实体。染色体作为遗传物质的主要载体,其内部表现(即基因型)是某种基因组合,它决定了个体的外部表现。因此,从一开始就需要实现从表现型到基因型的映射,即编码工作。初始种群产生后,按照优胜劣汰的原理,逐代演化产生出越来越好的近似解。在每一代,根据问题域中个体的适应度大小选择个体,并借助于自然遗传学的遗传算子进行组合交叉和变异,产生出代表新的解集的种群。这个过程将导致种群像自然进化一样,后代种群比前代更加适应环境,末代种群中的最优个体经过解码,可以作为问题近似最优解。 计算开始时,将实际问题的变量进行编码形成染色体,随机产生一定数目的个体,即种群,并计算每个个体的适应度值,然后通过终止条件判断该初始解是否是最优解,若是则停止计算输出结果,若不是则通过遗传算子操作产生新的一代种群,回到计算群体中每个个体的适应度值的部分,然后转到终止条件判断。这一过程循环执行,直到满足优化准则,最终产生问题的最优解。图1-1给出了遗传算法的基本过程。 1.2 遗传算法的特点 1.2.1 遗传算法的优点

遗传算法具有十分强的鲁棒性,比起传统优化方法,遗传算法有如下优点: 1. 遗传算法以控制变量的编码作为运算对象。传统的优化算法往往直接利用控制变量的实际值的本身来进行优化运算,但遗传算法不是直接以控制变量的值,而是以控制变量的特定形式的编码为运算对象。这种对控制变量的编码处理方式,可以模仿自然界中生物的遗传和进化等机理,也使得我们可以方便地处理各种变量和应用遗传操作算子。 2. 遗传算法具有内在的本质并行性。它的并行性表现在两个方面,一是遗传 开始 初始化,输入原始参 数及给定参数,gen=1 染色体编码,产生初始群体 计算种群中每个个体的适应值 终止条件的判断, N gen=gen+1 选择 交叉 Y 变异 新种群 输出结果 结束 图1-1 简单遗传算法的基本过程

基于Matlab的动态规划程序实现

动态规划方法的Matlab 实现与应用 动态规划(Dynamic Programming)是求解决策过程最优化的有效数学方法,它是根据“最优决策的任何截断仍是最优的”这最优性原理,通过将多阶段决策过程转化为一系列单段决策问题,然后从最后一段状态开始逆向递推到初始状态为止的一套最优化求解方法。 1.动态规划基本组成 (1) 阶段 整个问题的解决可分为若干个阶段依次进行,描述阶段的变量称为阶段变量,记为k (2) 状态 状态表示每个阶段开始所处的自然状况或客观条件,它描述了研究问题过程的状况。各阶段状态通常用状态变量描述,用k x 表示第k 阶段状态变量,n 个阶段决策过程有n+ 1个状态。 (3) 决策 从一确定的状态作出各种选择从而演变到下一阶段某一状态,这种选择手段称为决策。描述决策的变量称为决策变量,决策变量限制的取值范围称为允许决策集合。用()k k u x 表示第k 阶段处于状态k x 时的决策变量,它是k x 的函数。用()k k D x Dk(xk)表示k x 的允许决策的集合。 (4) 策略 每个阶段的决策按顺序组成的集合称为策略。由第k 阶段的状态k x 开始到终止状态的后部子过程的策略记为{}11(),(),,()k k k k n n u x u x u x ++ 。可供选择的策略的范围称为允许策略集合,允许策略集合中达到最优效果的策略称为最优策略。从初始状态* 11()x x =出发,过程按照最优策略和状态转移方程演变所经历的状态序列{ } **** 121,,,,n n x x x x + 称为最优轨线。 (5) 状态转移方程 如果第k 个阶段状态变量为k x ,作出的决策为k u ,那么第k+ 1阶段的状态变量1k x +也被完全确定。用状态转移方程表示这种演变规律,记为1(,)k k k x T x u +=。 (6) 指标函数 指标函数是系统执行某一策略所产生结果的数量表示,是衡量策略优劣的数量指标,它定义在全过程和所有后部子过程上,用()k k f x 表示。过程在某阶段j 的阶段指标函数是衡量该阶段决策优劣数量指标,取决于状态j x 和决策j u ,用(,)j j j v x u 表示。 2.动态规划基本方程 (){} 11()min ,,(),()k k k k k k k k k k f x g v x u f x u D x ++=∈???? Matlab 实现 (dynprog.m 文件) function [p_opt,fval]=dynprog (x,DecisFun,SubObjFun,TransFun,ObjFun) % x 是状态变量,一列代表一个阶段的所有状态; % M-函数DecisFun(k,x) 由阶段k 的状态变量x 求出相应的允许决策变量; % M-函数SubObjFun(k,x,u) 是阶段指标函数, % M-函数ObjFun(v,f) 是第k 阶段至最后阶段的总指标函数 % M-函数TransFun(k,x,u) 是状态转移函数, 其中x 是阶段k 的某状态变量, u 是相应的决策变量; %输出 p_opt 由4列构成,p_opt=[序号组;最优策略组;最优轨线组;指标函数值组]; %输出 fval 是一个列向量,各元素分别表示p_opt 各最优策略组对应始端状态x 的最优函数值。

如何编写MATLAB程序才能实现对

关闭文件用fclose函数,调用格式为:sta=fclose(fid)说明:该函数关闭fid所表示的文件。其调用格式为:[A,COUNT]=fscanf(fid,format,size)说明:其中A用来存放读取的数据,COUNT返回所读取的数据元素个数,fid为文件句柄,format用来控制读取的数据格式,由%加上格式符组成,常见的格式符有:d(整型)、f(浮点型)、s(字符串型)、c(字符型)等,在%与格式符之间还可以插入附加格式说明符,如数据宽度说明等。 matlab fprintf.数据的格式化输出:fprintf(fid, format, variables)fprintf(fid,format,A)说明:fid为文件句柄,指定要写入数据的文件,format是用来控制所写数据格式的格式符,与fscanf函数相同,A是用来存放数据的矩阵。>> fid=fopen(""d:\char1.txt"",""w"");>> fid1=fopen(""d:\char1.txt"",""rt"");matlab读txt文件fid=fopen(""fx.txt"",""r"");%得到文件号[f,count]=fscanf(fid,""%f %f"",[12,90]);%把文件号1的数据读到f中。 matlab函数fgetl和fgets:按行读取格式文本函数Matlab提供了两个函数fgetl和fgets来从格式文本文件读取行,并存储到字符串向量中。这两个函数集几乎相同;不同之处是,fgets拷贝新行字符到字符向量,而fgetl则不。下面的M-file函数说明了fgetl的一个可能用法。此函数使用fgetl一次读取一整行。while f eof(fid) == 0 tline = fgetl(fid); %用Fourier变换求取信号的功率谱---周期图法 clf; Fs=1000; N=256;Nfft=256;%数据的长度和FFT所用的数据长度 n=0:N-1;t=n/Fs;%采用的时间序列 xn=sin(2*pi*50*t)+2*sin(2*pi*120*t)+randn(1,N); Pxx=10*log10(abs(fft(xn,Nfft).^2)/N);%Fourier振幅谱平方的平均值,并转化为dB f=(0:length(Pxx)-1)*Fs/length(Pxx);%给出频率序列 subplot(2,1,1),plot(f,Pxx);%绘制功率谱曲线 xlabel('频率/Hz');ylabel('功率谱/dB'); title('周期图N=256');grid on; Fs=1000; N=1024;Nfft=1024;%数据的长度和FFT所用的数据长度 n=0:N-1;t=n/Fs;%采用的时间序列 xn=sin(2*pi*50*t)+2*sin(2*pi*120*t)+randn(1,N); Pxx=10*log10(abs(fft(xn,Nfft).^2)/N);%Fourier振幅谱平方的平均值,并转化为dB f=(0:length(Pxx)-1)*Fs/length(Pxx);%给出频率序列 subplot(2,1,2),plot(f,Pxx);%绘制功率谱曲线 xlabel('频率/Hz');ylabel('功率谱/dB'); title('周期图N=256');grid on; %用Fourier变换求取信号的功率谱---分段周期图法 %思想:把信号分为重叠或不重叠的小段,对每小段信号序列进行功率谱估计,然后取平均值作为整个序列的功率谱 clf;

labview与matlab接口的方法

LabVIEW与Matlab接口的方法 The Method of Interfacing Between LabVIEW and Matlab 陈金平 (新疆大学,乌鲁木齐 830008) 0 引言 虚拟仪器技术是计算机技术、现代测控技术和电子仪器技术相互结合、渗透的产物。在虚拟仪器系统中,数据的分析处理、控制、结果输出和用户界面等功能都由软件完成,硬件仅仅是为了解决信号的输入输出,因此,软件是整个仪器系统的核心,从某种意义上可以说:“软件即仪器”。虚拟仪器系统的软件设计可以采用通用的可视化编程语言,如Visual C++、Visual Basic、Delphi等,但更为方便高效的还是专用的虚拟仪器软件开发平台,如美国国家仪器公司(National Instruments,NI)的Lab2 VIEW、LabW indows/C VI,惠普公司的VEE等,而其中首推NI公司的图形化编程语言LabVIEW。 1 LabVIEW的功能及特点 LabVIEW是NI公司推出的一种虚拟仪器软件开发平台,自1986年正式推出,经过短短不到15年的时间,已经发展到以最新板本LabVIEW611为核心,包括控制与仿真、高级数字信号处理、统计过程控制、模糊控制和PID控制等众多附加软件包,运行于W indows NT/98、Linux、M acintosh、Sun和HP-UX等多种平台的工业标准软件开发环境。 LabVIEW在包括航空航天、通信、汽车、半导体和生物医学等众多领域内得到了广泛的应用。其最大的特色是采用编译型图形化编程语言———G语言(G raph2 Pro gramm ing),即用户设计好程序的大体框架后,如同画流程图一般,只需将系统提供的各种图形化功能模块连接起来,就可得到所需的应用软件。LabVIEW中的程序称为VI(virtual instruments),每个VI都由前面板和框图程序以及图标/连接端口三部分组成。 除了具备其它编程语言所提供的常规函数功能外,LabVIEW内部还集成了大量的生成图形界面的模板,如各种表头、旋钮、开关、LE D指示灯、图表等;丰富实用的数值分析、信号处理功能,如FFT变换、各种滤波器、信号发生器等;以及对RS-232、G PI B、VXI、数据采集板卡、网络等多种硬件的设备驱动功能,并免费提供数十家世界知名仪器厂商的几百种源码级仪器驱动,大大方便和简化了用户的设计开发工作。Lab2 VIEW使得过去繁琐、枯燥的软件开发变得简单、方便,尤其适合不熟悉传统文本编程语言(如C、BASIC等)的工程技术人员,被誉为工程师和科学家的语言。 但是,在大型的系统测试和仿真过程中,需要软件进行一些很复杂的数值计算时,LabVIEW的图形化编程语言就显得力不从心,M atlab是一种常用的高效率数学运算工具,它建立在向量、数组和复数矩阵的基础上,使用方便,将它和LabVIEW有机地结合起来会大大减少编程的工作量,提高编程效率。本文通过求解一常微分方程初值问题的例子,介绍了两种编程语言的接口方法。 2 在LabVIEW中调用Matlab语言的方法在测试系统设计和软件开发过程中,数学分析与信号处理是两个不可缺少的重要内容。LabVIEW将数据采集和测试分析中常用的数学和信号分析算法程序集成在一起,提供了先进的数学和信号分析环境,所有的数学分析节点都集中在M athematics子模板中。在此模板中有一M atlab Script节点,利用此节点就可以实现在LabVIEW中对M atlab语言的调用。下面通过具体例子介绍调用方法。举例如下: 用Runge2K utta法计算下列微分方程的解(初值问题): y′=-50y+50x2+2x , 0≤x≤1 y(0)=1 2.1 编制M文件 启动M atlab610,利用其M文件编辑器编写M文件如下: function y=ff2(x,y) y=-50?y+50?x?x+2?x; 35 LabVIEW与M atlab接口的方法 陈金平

matlab程序设计实例

MATLAB 程序设计方法及若干程序实例 樊双喜 (河南大学数学与 信息科学学院开封475004) 摘要本文通过对 MATLAB 程序设计中的若干典型问题做简要的分析和总结,并在此基础上着重讨论了有关算法设计、程序的调试与测试、算法与程序的优化以及循环控制等方面的问题.还通过对一些程序实例做具体解析,来方便读者进行编程训练并掌握一些有关MATLAB 程序设计方面的基本概念、基本方法以及某些问题的处理技巧等.此外,在文章的最后还给出了几个常用数学方法的算法程序, 供读者参考使用.希望能对初学者进行 MATLAB 编程训练提供一些可供参考的材料,并起到一定的指导和激励作用,进而为MATLAB 编程入门打下好的基础. 关键字算法设计;程序调试与测试;程序优化;循环控制 1 算法与程序 1.1 算法与程序的关系算法被称为程序的灵魂,因此在介绍程序之前应先了 解什么是算法.所谓算 法就是对特定问题求解步骤的一种描述.对于一个较复杂的计算或是数据处理的问题,通常是先设计出在理论上可行的算法,即程序的操作步骤,然后再按照算法逐步翻译成相应的程序语言,即计算机可识别的语言. 所谓程序设计,就是使用在计算机上可执行的程序代码来有效的描述用于解决特定问题算法的过程.简单来说,程序就是指令的集合.结构化程序设计由于采用了模块分化与功能分解,自顶向下,即分而治之的方法,因而可将一个较复杂的问题分解为若干子问题,逐步求精.算法是操作的过程,而程序结构和程序流程则是算法的具体体现. 1.2MATLAB 语言的特点 MATLAB 语言简洁紧凑,使用方便灵活,库函数极其丰富,其语法规则与科技人员的思维和书写习惯相近,便于操作.MATLAB 程序书写形式自由,利用其丰富

Matlab编程以及接口

Matlab编程的初步知识: 1.M脚本文件 Matlab命令集合; 无需输入和输出变量; 与其它脚本文件之间变量透明,即共同使用Matlab的工作空间。 比如 例1: x = (1:10); y =sin(x); plot(x,y) 例2: A = magic (4); B = A'; [C,D = xtimesAB(A,B); 2.函数 同样也是完成具体任务的指令集合,但是用一个名字封装起来,变量对外不透明,需要借助输入变量提供数据,输出变量给出结果。执行完毕后,所用的内存全部释放给Matlab。这样的命令集合体称为函数,封装的名字称为函数名,输入变量和输出变量在函数名前后指定。比如例2的xtimesAB(A,B)定义如下: function [C,D] =xtimesAB(A,B) % % This function can tell the products of e-e and V-C % C = A.*B; D = A*B; end 其中,函数名为xtimesAB,输入变量为A,B;输出变量为C,D。函数名下面%开头的部分为注释内容。在Matlab环境下,可以通过help xtimesAB来显示。 还有一种简单的函数,即inline函数,其特点是随用随定义。比如 1.>> myfun = ‘1+log(r) ‘; 2.>> myfuni=inline(myfun,’r’) 3.>>a=feval(myfuni,10) 4.结果a = 3.3026

我们用得最多的,就是像xtimesAB这样的M函数。与上面这个inline函数对应的M函数为 function y=myfun(r) y=1+log(r); 该函数结尾不含有end,即Matlab不要求必须有end。 使用时,在Matlab命令环境下,直接书写函数名,并给出输入变量,即可以工作。但需要注意的是,Matlab调用的是文件名而不是函数名。但一般两者取一样的名字。因此,关键是文件名。 M函数的流程控制简介如下: I. 循环 5.while a)while condition b)命令语句 c)end 6.for a)for i=1:n b)语句 c)end ii.条件 1.if a)if condition 1 b)语句 c)elseif condition2 d)语句 e)else f)语句 g)end 2.switch a)switch 表达式 b)case case1 c)语句 d)case case2 e)语句 f)otherwise g)语句 h)End iii.跳过:continue iv.跳出:break

第13章 MATLAB外部程序接口技术_习题答案

1 第13章 MATLAB 外部程序接口技术 习题13 一、选择题 1.要在Word 环境下调用MATLAB 的命令,需要调用Word 的( )模板。B A .Normal B .M-Book C .自由格式 D .空白文档 2.在Excel 环境下加载Spreadsheet Link 程序后,会在Excel 窗口的“开始”选项卡中增加一个( )命令组。D A .Excel B .Spreadsheet C .Link D .MATLAB 3.打开一个可读可写的文本文件,其打开方式为 。A A .rt+ B .r+ C .rwt D .a 4.以下选项中,用于定义指向MAT 文件指针的命令是( )。A A .MA TFile *p; B .MAT *p; C .File *p; D .FIL E *p; 5.关于MATLAB 引擎,下列说法中不正确的是( )。C A .利用MA TLA B 引擎,可以在 C 程序中调用MA TLAB 的函数。 B .通过MATLAB 引擎,可以提高开发应用程序的效率。 C .通过MA TLAB 引擎,可以在MA TLAB 中直接调用用C 语言编写的函数 D .包含MA TLAB 引擎函数的程序的执行效率减低。 二、填空题 1.在Word 与MATLAB 之间进行传递的内容称为 ,由M-Book 文档传向MATLAB 的命令称为 ,M-Book 文档中的MATLAB 命令的执行结果称为 。单元(Cell ),输入单元(Input Cell ),输出单元(Output Cell ) 2.Excel 和MA TLAB 的交互操作,通过 程序来实现。Spreadsheet Link 3.MA TLAB 文件操作的基本步骤是,先 文件,在对文件进行 ,最后 文件。打开,读写,关闭 4.对MAT 文件进行操作的C 程序中,一定要包含 头文件。mat.h 5.MEX 函数在头文件 中得到声明。mex.h 三、应用题 1.在MA TLAB 中创建一个100 × 200的随机矩阵,然后将数据导入到Excel 表格中,在Excel 中调用MATLAB 的差分函数按列进行差分运算。 2.已知)2ln(x y + =π,当x 取-3.0、-2.9、-2.8、…、2.8、2.9、3.0时,求各点的 函数值。要求: (1)将函数值输出到一个数据文件中。

多目标优化实例和matlab程序

NSGA-II 算法实例 目前的多目标优化算法有很多,Kalyanmoy Deb 的带精英策略的快速非支配排序遗传算法(NSGA-II)无疑是其中应用最为广泛也是最为成功的一种。本文用的算法是MATLAB 自带的函数gamultiobj ,该函数是基于NSGA-II 改进的一种多目标优化算法。 一、数值例子 多目标优化问题 42422 11211122124224212212112 12min (,)10min (,)55..55 f x x x x x x x x x f x x x x x x x x x s t x =-++-=-++-≤≤??-≤≤?二、Matlab 文件 1.适应值函数m 文件: function y=f(x) y(1)=x(1)^4-10*x(1)^2+x(1)*x(2)+x(2)^4-x(1)^2*x(2)^2; y(2)=x(2)^4-x(1)^2*x(2)^2+x(1)^4+x(1)*x(2);2.调用gamultiobj 函数,及参数设置: clear clc fitnessfcn=@f; %适应度函数句柄nvars=2; %变量个数lb=[-5,-5]; %下限ub=[5,5]; %上限A=[];b=[];%线性不等式约束 Aeq=[];beq=[];%线性等式约束 options=gaoptimset('paretoFraction',0.3,'populationsize',100,'generations',200,'stallGenLimit',200,'TolFun',1e-100,'PlotFcns',@gaplotpareto); %最优个体系数paretoFraction 为0.3;种群大小populationsize 为100,最大进化代数generations 为200, %停止代数stallGenLimit 为200,适应度函数偏差TolFun 设为1e-100,函数gaplotpareto :绘制Pareto 前端 [x,fval]=gamultiobj(fitnessfcn,nvars,A,b,Aeq,beq,lb,ub,options)

相关文档
相关文档 最新文档