Академический Документы
Профессиональный Документы
Культура Документы
, 2006
519.68
32.913
51
. ., . ., . .
51 Borland C++ Builder
MATLAB /++. .: , 2006. 496 .: .
ISBN 5940743102
.............................................................................. 10
Borland C++ Builder
++ 1.
MATLAB. Borland C++ Borland C++ Builder
Builder MATLAB, MATLAB 1.1. ................................................................ 13
/++ MATLAB.
1.1.1. .................................................... 14
Borland C++ Builder,
1.1.2. ................................................... 14
MATLAB ++.
MATLAB Borland C++ Builder 1.1.3. ............................................................. 14
Windows , 1.1.4. ............................................................... 14
. 1.1.5. ...................................................... 15
1.1.6. ........................................................ 16
, , 1.1.7. ........................................................ 16
++, 1.1.8. ..................................................... 16
++, MATLAB, 1.2. C++ Builder ....................................................... 17
++ 1.2.1. .................................................. 18
Borland C++ Builder MATLAB
1.2.2. ................................................... 18
MATLAB .
1.2.3. .................................................... 19
1.3. ++ C++ Builder ..... 19
1.3.1. ................................................................ 19
1.3.2. ........................................................... 20
1.3.3. ............................................................. 21
519.68 1.3.4. ..................................................................... 22
32.913 1.3.5. ........................................................ 23
1.3.6. ...................................................... 27
MATLAB is a trademark of The MathWorks, Inc. and is used with permission. The 1.3.7. ............................................... 28
MathWorks does not warrant the accuracy of the text or exercises in this book. This books use or ...................................................................... 29
discussion of MATLAB software or related products does not constitute endorsement or
sponsorship by The MathWorks of a particular pedagogical approach or particular use of the
1.3.8. ........................................................................ 32
MATLAB software. 1.3.9. )
................................................................ 33
. ., . ., 1.3.10. ++ ...................................... 51
. ., 2006 1.3.11. ................................. 54
ISBN 5940743102 ,. , 2006 1.4. VCL .............. 58
4 5
1.1.
C++ Builder (SDI),
( ) ,
( )
( ). , C++
1.1.2. 1.1.5.
.
,
( ActiveX),
. : ,
. C++ Builder
, , Properties () Events ().
. .
C++ Builder , ,
, .
. .
Properties ,
. ,
1.1.3. .
C++ Buil , .
der. ,
() C++ Builder .
. (, Font) . ,
, , . ,
, ( ) . , ,
, :
.
, .
TLabel *Label1 ( public ).
.
, ,
Events ,
Shift, ,
. ,
.
,
.
. ,
,
1.1.4. . ,
(ClassExplorer) . .
, .
16 1. 1.2. C++ Builder 17
1.1.6.
, ( ),
. ,
.
, View/Project Manager.
Project1.cpp.
. 1.1.2.
. 1.1.3.
.
. :
( C++ Builder.
) Add <F1>.
, , ,
. (VCL).
. , , .
, ,
. , 1.2. C++ Builder
Remove . C++ Builder ++,
Options ,
(. 1.1.3), . C++ Builder .
, , ,
. , .
, ,
1.1.7. .
C++ Builder , , , . . ,
, , ,
. .
,
.
1.1.8. (,
, C++ Builder , ,
, . .)
18 1. 1.3. ++ 19
, ,
. { }.
, .
,
.
. 1.1.4.
1.2.1.
,
. ,
, ,
(, ).
(published) .
published, (public) . 1.1.5.
, .
. 1.2.3.
,
1.2.2. ++, .
, ,
(Events) , ->, :
, . Edit1->Show();
( , Mic
rosoft Windows)
,
1.3. ++
C++ Builder
. .
C++ Builder ( C++, C++ Builder.
), , ,
. , ,
, . ++
, .
(
), ,
1.3.1.
, C++ Builder
. , ,
20 1. 1.3. ++ 21
, .
C++ : ,
/* , */. . long,
(, short, signed unsigned. limits.h
). .
, (
) . , /* */
. char, short, int long
// , .
, . :
. char, signed char, ,
. char ;
// , unsigned char;
/* */, /* //. char, unsigned char, ,
, char ;
, signed char;
. , int, signed int;
, unsigned, unsigned int;
, short, short int, signed short int;
. unsigned short, unsigned short int;
long, long int, signed long int;
1.3.2. unsigned long, unsigned long int.
signed unsigned char,
, , . short, int long.
, signed unsigned, signed int
int MaxSize; unsigned int.
, MaxSize int, MaxSize long short int,
. , .
. ANSI C
. , +, , * /. , , (short, int long),
stream.h, int sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long).
<<, ostream. ,
, . 32 C++ Builder int long
. , 32 . char, , .
, . C++ sizeof(float) <=
. sizeof(double).
. , , ,
1.3.3. .
:
char __int8 long
double __int16 signed
float __int32 short , C
int __int64 unsigned . C++ Builder
22 1. 1.3. ++ 23
),
. . , sizeof (add
, struct
ress) 24, 22, .
() . :
, ,
struct address { // , ,
char* name; //
long number; //
. :
char* street; // struct link{
char* town; // link* previous;
char* country[2]; // link* successor;
int zip; // }
}; ,
, address ( ), ,
, , . struct no_good {
. no_good member;
};
C++, ,
. . ( )
address , ,
, . . :
(). : struct list; //
p = &c; // p c
d = *p; // *p ( )
,
,
. ,
( ), , enum, :
, .
enum days {su, mo, tu, we, th, fr, sa};
new, delete.
:
,
char *buffer;
buffer = new char; // enum modes {LASTMODE = -1, BW40=0, C40, BW80, C80, MONO = 7};
// LASTMODE 1, C40, BW80 C80
... 1, 2 3, MONO 7.
delete buffer; //
, .
days A;
: //...
char *buffer; A = we;
buffer = new char[256]; // 256 //...
... for (days i=su; i<=sa; i++) {...};
//...
delete[] buffer; // ,
if (A == th) {...};
//
,
. C++ Builder Borland
1.3.6.
Delphi ,
. :
>. + , ;
: , ;
address *p = new address; * ;
... / .
p->name = ; :
p->number = 34 ;
== ;
-> != ;
* .. , < ;
: > ;
(*p).name = ; <= ;
(*p).number = 34 ; >= .
, , ,
: , 7/2 3. %
TList *MyList; , , 7%2 1.
TItem *Item;
MyList = new TList(); //
//
Item = new TItem(125, Hello, 34.032); //
a + b, a b
// , C++ Builder
... , .
MyList->Add(Item); //
...
. ,
delete MyList; //
// ( . ) .
28 1. 1.3. ++ 29
double d = 1; ,
int i = 1;
.
d = d + i;
i = d + i;
( ), C++ Builder , (, ,
. . .) . ,
1. , ,
. :
. 1.1.3.
int n;
, ,
double x_min;
int ( ), double, float long double.
2. long double, n = 1002;
long double. x_min = -54.196;
3. , double, .
double. ,
4. , float, ()
float. . :
5. , unsigned long, for (int i = 1; i; i++) ...
unsigned long. const float pi = 3.14;
double tau = pi*3/4;
6. , long,
long.
7. , unsigned, , :
unsigned. .
8. , int ( ). (, &
, & ),
1.3.3. , (+ a+b
, float, , int).
, ,
char int , ,
.
unsigned char int
signed char int , 1.3.4.
short int
unsigned short unsigned int
~ ( )
enum int &
^
, . |
<<
>>
1.3.7.
C++ , C++ =, ,
. . ,
, , x=sqrt(a=3*x). . a=b=c
, . . , c b, a.
30 1. 1.3. ++ 31
, , if .
. , x[i+3]*=4 x[i+3]=x[i+3]*4,
, x[i+3] . switch
C++ . switch
* ( , . :
), *p , p. switch (ch) {
. , case 'i':
in = x;
char* p, *p , p.
cm = x*fac;
break;
case 'c':
. in = x/fac;
, . : cm = x;
a = b*3+c; break;
cout << "go go go"; default:
lseek(fd,0,2); in = cm = 0;
break;
: }
;
break switch.
. , case ,
, . , default.
default .
(, ) , while
. : , p
{ a=b+2; b++; }
q .
. 0.
, , . while (*p != 0) {
. *q = *p; //
q = q+1;
if p = p+1;
++ . ( ? : ) };
: , , *q = 0; // 0
. while .
. : , ,
int a, b ,c ,d; . ,
... .
return ((a>b)? c : d);
: for
if ( 1 ){ :
... for (int i=0; i<10; i++) q[i]=p[i];
}
else if ( 2 ){
int i = 0;
...
} while (i<10) {
else{ q[i] = p[i];
... i++;
}; }
32 1. 1.3. ++ 33
for , , , ,
, . ++ ,
. . ,
, . ,
, , ,
, :
, , . overload pow;
int pow(int, int);
double pow(double, double);
1.3.8. //...
x=pow(2,10);
, y=pow(2.0,10.0);
, .
overload ,
. ,
pow
2:
. ,
extern float pow(float, int); //pow()
main(){
.
for (int i=0; i<10; i++) cout << pow(2,i) << \n; , ++ .
} void ().
, , pow , , void:
float int float. void swap(int* p, int* q){ //
int t = *p;
,
*p = *q;
. extern , *q = t;
, }
().
, 1.3.9. ,
. . ,
pow(12.3,"abcd") , "abcd"
, int. pow(2,i) 2 float, C++,
. pow , , :
#include <VCL> , , ,
void error(char* p){ // , , . ,
ShowMessage(p); . ,
exit(1);
}
,
. ,
float pow(float x, int n){ ,
if (n < 0) error(", pow()"); . , .
switch (n) { ,
case 0: return 1;
case 1: return x; ( )
default: return x*pow(x,n-1); ++Builder.
}
}
} (class).
, , .
( ) ( ). (struct),
return. .
34 1. 1.3. ++ 35
, , , void date::next(){
, . if ( ++day > 28 ) { //
...
, }
. }
, .
, , .
, ( , .
, ), . . date
, . , ,
. date .
. , struct class:
. class date{
int month, day, year;
struct, date public:
: void set(int, int, int);
void get(int*, int*, int*);
struct Date { int month, day, year; }; void next();
date today; // : , , void print();
}
};
void set_date(Date*, int, int, int); public . ()
void next_date(Date*); . , (public)
void print_date(Date*);
// ... . struct class,
,
.
, . :
, :
void date::print(){
struct Date {
cout << day << "/" << month << "/" year;
int month, day, year;
}
void set(int, int, int);
void get(int*, int*, int*); , , ,
void next(); date. :
void print();
}; void backdate(){
today.day; //
, , ( }
) , ,
. : , . , ,
Date today; // (, 36, 1985),
Date my_burthday; //
, , ,
void f(){ , . ,
my_burthday.set(21,6,1951); date ,
today.set(18,11,2005);
. ,
my_burthday.print(); ,
today.next(); .
}
,
: , . :
36 1. 1.3. ++ 37
class x { list_head->append(b);
int m; }
public:
, ,
int readm() { return m; }
}; this, pre suc (,
). dlink, dlink::append()
x aa; . C++ class,
x bb;
.
void f(){
int a = aa.readm();
int b = bb.readm(); set_date() (
// ... ) . ,
}
,
m aa, bb. ( , , )
, , . :
. this. , .
x this , .
x* this;
, , . :
, , .
class date {
this , . x // ...
: date(int, int, int);
class x { };
int m; ,
public:
int readm() {return this->m;}
. ,
}; :
this . date today = date(23,6,1983); //
//today date
this , date xmas(25,12,0); // (xmas - )
. , date my_burthday; // ,
:
class dlink { . , . :
dlink* pre; //
dlink* suc; // class date {
public: int month, day, year;
void append(dlink*); public:
// ... // ...
date(int, int, int); // , ,
};
date(char*); //
date(int); // ,
void dlink::append(dlink* p){
date(); // :
p->suc = suc; // p->suc = this->suc
};
p->pre = this; // this
suc->pre = p; // this->suc->pre = p
suc = p; // this->suc = p , .
}
,
dlink* list_head; :
date today(4);
void f(dlink*a, dlink *b){ date july4(" 4, 1983");
// ... date guy("5 ");
list_head->append(a); date now; //
38 1. 1.3. ++ 39
,
overload. , ,
, , , , .
overload , ,
. . xclass
date . ~xclass() ( ). ,
, ,
, . , ,
, , , , , :
, . class char_stack {
. date int size;
, char* top;
char* s;
: . public:
class date { char_stack(int sz) { top = s = new char[size = sz];}
int month, day, year; ~char_stack() { delete[] s; } //
public: void push(char c) { *top++ = c; }
// ... char pop() { return *top;}
date(int d =0, int m =0, int y =0); };
date(char*); //
};
char_stack , :
void f(){
date::date(int d, int m, int y) { char_stack s1(100);
day = d ? d : today.day; char_stack s2(200);
month = m ? m : today.month; s1.push('a');
year = y ? y : today.year; s2.push(s1.pop());
// , char ch = s2.pop();
// ... cout << chr(ch) << "\n";
} }
, f(), s1 char_stack,
. day 100 , s2,
mounth , , year . 200 . f() .
, . 1 . . . (year==1)
Inline
1 . . . (year==1),
.
. , ,
. , ,
. : . , , ,
. ,
date d = today; //
(
, ) , ,
++, .
VCL, C++ Builder. , inline . ,
Assign. : , ( )
TBrush *MyBrush = new TBrush(); , inline. , , ,
...
// MyBrush char_stack, , ,
// PaintBox1 ! ,
MyBrush->Assign(PaintBox1->Canvas->Brush); ,
40 1. 1.3. ++ 41
. , ,
. inline table,
. : table . . :
class char_stack { #include "table.h"
int size;
char* top; table globals;
char* s; table keywords;
public: ...
char pop(); table* locals = new table;
// ... ...
};
table::look(),
inline char char_stack::pop() { name :
return *top; #include
} name* table::look(char* p, int ins){
for (name *n = tbl; n; n=n->next)
if (strcmp(p, n->string) == 0) return n;
, ,
if (ins == 0) error(" ");
. ,
. , , , name *nn = new name;
. . , nn->string = new char[strlen(p)+1];
. strcpy(nn->string, p);
nn->value = 1;
, , nn->next = tbl;
. tbl = nn;
. return nn;
, . };
, ( ) . table, ,
, . .
, ,
table,
, , , , :
, . class table {
: name** tbl;
int size;
struct name {
public:
char* string;
table(int sz = 15);
char* next;
~table();
double value;
name* look(char*, int = 0);
};
name* insert(char* s) { return look(s,1); }
table: };
// table.h ,
class table {
.
name* tbl;
public: . ,
table() { tbl = 0; } , ,
. ,
name* look(char*, int = 0);
name* insert(char* s) { return look(s,1); }
, .
}; :
42 1. 1.3. ++ 43
table::~table(int sz){ . @
if (sz < 0) error( );
, operator@,
tbl = new name*[size=sz]; . :
for (int i = 0; inext){ class ostream {
delete n->string; //...
delete n; ostream operator<<(char*);
} };
, delete,
C++ , .
. ,
,
, . . :
.
.
class vec: public vector {
class vector { int low, high;
int* v; public:
int sz; vec(int,int);
public: int& elem(int);
vector(int); // int& operator[](int);
~vector(); //
};
int size() { return sz; }
void set_size(int); vec :public vector , vec
int& operator[](int); vector. vec ()
int& elem(int i) { return v[i]; }
};
vector ,
. , vector vec, vec
size ,
vector. vec vector ,
0 ... size()-1. set_size
,
, elem
, elem(int)
, operator[] .
operator[](int). elem() vec
,
elem() vector:
, ,
int& vec::elem(int i){
new: return vector::elem(i-low);
vector::vector(int s){ }
if (s<=0) error(" ");
sz = s; :: ,
v = new int[s]; vec::elem() .
} vec::elem() ,
vector , v vector,
++: .
vector v1(100); :
vector v2(nelem*2-4); vec::vec(int lb, int hb) : (hb-lb+1) {
: if (hb-lb<0) hb = lb;
int& vector::operator[](int i){ low = lb;
if(i<0 || sz<=i) error(" "); high = hb;
}
return v[i];
} : (hb-lb+1)
, , vector::vector().
: vec::vec().
v1[x] = v2[y];
:
~vector ,
class vec : public vector {
. public:
vector::~vector(){ vec (int s) : (s) {};
delete v; ~vec(){};
} void operator=(vec&);
46 1. 1.3. ++ 47
void operator*=(vec&);
void operator*=(int);
//... , ,
}; , ,
. , ,
vec::vec(), .
vector::vector() . (class) (struct).
: ,
void vec::operator=(vec& vect){ :
set_size(vect.size()); class element { //
for (int i=0; i<size(); i++) elem(i) = vect.elem(i); //...
}; };
,
class cvector {
() (). element** v;
//...
, (friends) public:
, , , cvector(int);
element*& elem(int);
.
element*& operator[](int);
(friend). //...
operator+(). };
, . ,
, , , , vector
. , element . :
vector::elem() i class apple : public element { /*...*/ }
.
class orange : public element { /*...*/ }
//...
. , , cvector fruitbowl(100);
friend. , : //...
apple aa;
class vec; // vec -
orange oo;
//...
class vector {
fruitbowl[0] = &aa;
friend vec operator+(vec, vec);
fruitbowl[1] = &oo;
//...
}; , apple orange
: element. ,
//
, ,
vec operator+(vec a, vec b){ . , ,
int s = a.size(); element, apple orange .
if (s != b.size()) error(" "); ,
vec& sum = *new vec(s);
, .
int* sp = sum.v;
int* ap = a.v; ( C++ Builder
int* bp = b.v; , , ,
while (s)
*sp++ = *ap++ + *bp++; ), ,
return sum; .
} , , apple
48 1. 1.3. ++ 49
class apple_vector : public cvector { a.x = x1; a.y = y1; b.x = x2; b.y = y2; c.x = x3; c.y = y3; };
public: void draw();
apple *& elem(int i) {return (apple*&) cvector::elem(i);} void rotatte(int i);
//... //...
}; };
element*& ( element), draw() circle
cvector::elem, apple*&. , shape radius,
( triangle a, b, c.
), rotatte() ,
, i .
. ,
. , :
, . class shape_vector : public cvector {
shape, public:
shape: shape*& elem(int i) {return (shape *&) cvector::elem(i);}
void draw_all() {for (int i=0; i<size(); i++) elem(i)->draw() };
struct point { //...
int x, y; };
};
class shape : public element{ shape_vector drawing(5);
point center; // ...
color col; drawing[0] = new triangle(10,2, 40,23, 67,11);
//... drawing[1] = new circle (58, 37, 32);
public: drawing[2] = new triangle(45,12, 54,23, 87,32);
shape(point o){center = o}; drawing[3] = new triangle(34,23, 65, 21, 11, 67);
shape(int x0, int y0) {center.x = x0; center.y = y0;}; drawing[4] = new circle(33,42, 12);
void move(point to) { center=to; draw();} // ...
point where() { return center;} drawing.draw_all();
virtual void draw();
virtual void rotate(int); ,
//... draw()
}; (shape*), (triangle* circle*),
.
, . move (
) where (). ,
, , ,
virtual. : , ,
class circle: public shape { . ., . :
int radius; #include
public: class color {
circle (int x, int y, int r) : (x, y) {r = radius;}; public:
void draw(); virtual ~color() { //
void rotatte(int i) {}; std::cout << " color\n";
//... };
}; };
}; :
;
class brightred : public red {
public: ;
~brightred() { // 1...N (
std::cout << " brightred\n"; );
}
};
1...N ( );
GetName ;
color *palette[3]; SetName .
//...
palette[0] = new red;
.
palette[1] = new brightred; .
palette[2] = new color; :
[virtual] GetName (1 1, ... ,N N);
// red color.
[virtual] void SetName (1 1, ... ,N N, );
delete palette[0];
std::cout << std::endl; :
;
// bright, red color.
;
delete palette[1];
std::cout << std::endl; 1...N (
);
// color. 1...N ( );
delete palette[2];
GetName ;
: SetName ;
red .
color
:
brightred class Famille {
red private:
color AnsiString FNames[10];
virtual AnsiString GetName(int Index);
color virtual void SetName(int, AnsiString);
public:
,
Famille(){}
~Famille(){}
. __property AnsiString Names[int Index] = {read=GetName,
write=SetName};
};
Names AnsiString .
. , ,
(). , 1.3.10. ++
,
,
.
.
, ,
, , ++
.
main WinMain
:
MS Windows.
__property = {read=GetName, write=SetName};
__property [1 1]... [N N] = {read=GetName,
. main:
write=SetName}; int main(int argc, char * argv[], char * env[]) {};
52 1. 1.3. ++ 53
: }
return 0;
argc ;
}
argv ;
env .
,
int (0 , .
1..32764 ).
WinMain:
int WINAPI WinMain(HANDLE hInstance, HANDLE hPrevInstance, LPSTR . ,
lpszCommandLine, int cmdShow ) {}; , (, 1000,
: 10 000 , ) .
hInstance 1 ; (),
hPrevInstance , (,
; ) . ,
lpszCommandLine ; C++ Builder (
cmdShow (); ).
int . , ,
C++ Builder MS Windows , , , . .,
: .
#include <vcl.h> ++, , :
#pragma hdrstop ( ), (
//
USEFORM(Unit1.cpp, Form1); , , . .), (
// , ). ,
WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) ,
{
try ,
{ .
Application->Initialize(); ,
Application->CreateForm(__classid(TForm1), &Form1);
Application->Run();
, . ,
}
catch (Exception &exception) .
{ . sqrt
Application->ShowException(&exception);
} math.h,
catch (...) msqrt2 math1, math1.h math1.cpp.
{ :
try
{ // math1.h
throw Exception(); #include <math.h>
} double msqrt2 (double x);
catch (Exception &exception) // math1.h
{
Application->ShowException(&exception); // math1.cpp
} #include "math1.h"
: , ,
#include "math1.h" .
... ,
x = msqrt2(4); . :
include void main {
<math.h> , //
( $(BCB)\include;$(BCB)\include\vcl, TMouseState State = GetMouseBtnState();
$(BCB) C++ Builder). , TPoint Pos = GetMousePosition(); //
( )
, . , if (State == LeftBtnDown) { }
math.h elseif (State == RightBtnDown)
{ }
, , math1.h . elseif ((State == LeftBtnDown)&&( State == RightBtnDown))
{ };
, C++ Builder char ch = GetKeyChar(); //
. , ,
swith (ch) {
: case a: { a}; breake;
(project source file) (Project1.cpp) ...
WinMain , C++ Builder ; case : { a}; breake;
};
(Unit1.cpp) (Unit1.h). };
, ,
,
(C++ Builder
. ,
, ). ,
, ,
,
, ( .
, , , :
) .
void main {
, , bool IsWork = true;
;
(Unit1.dfm) while (IsWork) {
//
; TMouseState State = GetMouseBtnState();
(Project1.res) , //
(, TPoint Pos = GetMousePosition();
. .); if (State == LeftBtnDown) LeftBtnDown Proc();
(Project1.bpr) else if (State == RightBtnDown) RightBtnDownProc();
. elseif ((State == LeftBtnDown)&&
( State == RightBtnDown)) LeftRightBtnDownProc();
1.3.11. //
char ch = GetKeyChar();
swith (ch) {
, case a: KeyADownProc(); breake;
...
MS Windows, , case x: IsWork = false; breake;
, , case z: KeyADownProc(); breake;
. , };
56 1. 1.3. ++ 57
}; ,
};
,
, , ,
, . . C++ Builder.
, , ,
, ,
.
, ( VCL),
. , , .
void MessageProc(int Handle, int Message, int Parameter); . , C++ Builder ,
: .
Handle ; , , ,
Message ; ,
Parameter , . . ,
.
:
C++ Builder ,
void main {
bool IsWork = true;
C++ Builder.
// - , (Events)
TMouseState PrevState = stNull; . , , ,
//
TPoint PrevPos = GetMousePosition();
.
while (IsWork) { .
// (TEdit) (TButton).
TMouseState State = GetMouseBtnState(); , :
//
TPoint Pos = GetMousePosition(); void __fastcall TForm1::Button1Click(TObject *Sender)
int Handle = GetHandle(); // {
// , int x, y;
for (int i = 0; i < 500; i++){
if (State != PrevState) { // Randomize();
if (State != stNull)
MessageProc(Handle, mesMouseDown, State); for (int j = 0; j < 64000; j++)
else y = random(j);
MessageProc(Handle, mesMouseUp, State);
}; x = random(i);
}
if (Pos != PrevPos) MessageProc(Handle, mesMouseMove, State);
Edit1->Text = " 1 ";
char Ch = GetKeyChar(); // }
if (Ch != ) MessageProc(Handle, mesKeyPress, Ch);
}; void __fastcall TForm1::Button2Click(TObject *Sender)
}; {
int x, y;
for (int i = 0; i < 500; i++){
. ( Randomize();
) , for (int j = 0; j < 64000; j++){
y = random(j);
.
, , , Application->ProcessMessages();
, , . ., }
58 1. 1.4. VCL 59
x = random(i); 1.4.1.
}
Edit1->Text = " 2 "; AnsiString()
} AnsiString(const char* src) AnsiString
, OwnerName = ;
. char*, wchar_t*
AnsiString(const wchar_t* src)
, .
AnsiString(const AnsiString& src)
, AnsiString(const WideString &src)
, , . AnsiString(const char* src, unsigned int len) len
src
Application->ProcessMessages(); AnsiString(char src)
AnsiString(int src)
.
AnsiString(double src)
, AnsiString(short) ,
, , AnsiString(unsigned short) 15)
. , AnsiString(unsigned int)
. , AnsiString(long)
, . AnsiString(unsigned long)
AnsiString(__int64)
AnsiString(unsigned __int64)
1.4.
VCL Delete
C++ Builder AnsiString& Delete(int index, int count);
(VCL) , , , , count ,
, . ., index, 1 .
. C++ . index ,
Builder, AnsiString , 1, . count
. , ,
index, Delete . count , 0,
1.4.1. . :
AnsiString s = "";
s.Delete(3, 2);
VCL, C++. : s = ""
.
Insert
AnsiString
AnsiString& Insert(const AnsiString& str, int index);
++
Insert str AnsiString,
. AnsiString C++ Builder
index, 1 .
Object Pascal. AnsiString
. index 1, 1 .
, :
index , , Length().
AnsiString FNames[10]; // 10
AnsiString OwnerName = " ";
str , Insert .
AnsiString s = "";
. s.Insert("2", 4);
, . 1.4.1: : s = "2"
60 1. 1.4. VCL 61
Pos UpperCase ,
. .
int Pos(const AnsiString& subStr); []. [] idx.
Pos subStr , 1 AnsiString s = "";
. , 0. char c = s[5];
: c =
AnsiString s = "";
int i = s.Pos(""); + +=. + .
: i = 3. AnsiString s1 = "";
AnsiString s2 = "2";
SetLength AnsiString s = s1 + s2;
: s = "2"
AnsiString& SetLength(int newLength);
SetLength newLength, += .
. AnsiString s1 = "";
AnsiString s2 = "2";
s1 += s2;
SubString : s1 = "2"
AnsiString SubString(int index, int count); .
SubString AnsiString, count .
, index.
AnsiString s= ""; 1.4.2.
AnsiString s1=s.SubString(2, 4);
: s1 = ""
!=
Trim < <
<= <=
AnsiString Trim();
== ==
Trim , > >
. >= >=
62 1. 1.4. VCL 63
, .
Copy CopyRange.
, void foo(DynamicArray <int> &i_array){
// temp i_array
, VCL. , DynamicArray <int> temp = i_array;
sysdyn.h, if (temp == i_array){ // temp i_array
DynamicArray: //
DynamicArray < > ; i_array[0] = 20; // temp[0] i_array[0] 20
temp = i_array.Copy(); // temp
: temp[0] = 10; // i_array[0] 20, temp[0] 10
; }
. }
: .
DynamicArray <int> arrayOfInt;
, . Length
, :
typedef DynamicArray < DynamicArray < AnsiString > > T2DStringArray;
Length:
arrayOfInt.Length = 10; void foo(T2DStringArray &s_array){
cout << "ArrayLength: " << arrayOfInt.Length << endl; SetLength(s_array, 10);
SetLength:
//
SetLength(arrayOfInt, 20); for (int i=0; i<s_array.Length; i++){
, SetLength(s_array[i], i+1); //
, , for (int j=0; j<s_array[i].Length; j++)
s_array[i][j] = itoa(i*10+j);
. , }
. }
0 Length.
[]: TList
void InitArray(DynamicArray <char> &c_array){ TList
c_array[0] = 'A'; , , .
c_array[1] = 'B';
cout << 'Third char is: ' << c_array[2]; , TList ,
} .
Low High . TList
. :
int TotalArray(const DynamicArray <int> &arrayOfInt){ TList *List = new TList();
int total=0;
, // , TEdit
. int AnyNumber;
bool IsNumberOk;
, , :
Label1->Caption = " "; ...
// OnCreate , TEdit
1.4.15. TLabel, TControl
void __fastcall TForm1::FormCreate(TObject *Sender)
{
OnMouseEnter(TObject *Sender) , ...
// ,
// .
OnMouseLeave(Tobject *Sender) , // , 0,
// .
AnyNumber = 0;
TEdit // false ,
TEdit (AnsiString) //
, IsNumberOk = false;
...
. . };
TPanel
1.4.27. TScrollBar
TPanel
. (TBevel)
TScrollBarKind Kind , :
.
enum TScrollBarKind { sbHorizontal, sbVertical }
BevelInner,
Word LargeChange <Page Up>,
<Page Down> BevelOuter, BevelWidth,
int Max . TPanel
int Min , , (,
int PageSize TRadioButton) . .
80 1. 1.4. VCL 81
1.4.39. TForm . .
,
OnActivate(TObject* Sender) , File\Open.
ShowModal()
OnDeactivate(TObject* Sender) , ModalResult. , :
OnCanResize(TObject* Sender, 1. , .
int &NewWidth, int &NewHeight, , 2. BorderStyle bsDialog,
bool &Resize) NewWidth, NewHeight. .
, Resize = false 3. Visible false,
OnClose(TObject* Sender, , ) .
TCloseAction &Action) 4.
OnCloseQuery(TObject* Sender, .
bool &CanClose) . CanClose false, 5. TButton ( ,
TBitBtn), ModalResult, , , mrOk
OnCreate(TObject* Sender) mrCancel,
ModalResult .
OnDestroy(TObject* Sender) 6. , :
OnHide(TObject* Sender) ,
void __fastcall TForm1::Button1Click(TObject *Sender){
if (Form2->ShowModal() == mrOk)
90 1. 1.4. VCL 91
MessageBeep(0); Child->Memo1->Lines->LoadFromFile(Name);
}
,
, . ActiveMDIChild ,
, ,
. ShowModal() .
,
. TFont
, , TFont
ShowModal(). MS Windows. ,
(SDI). .
. .
C++ Builder .
. , (SDI) 1.4.40. TFont
, ,
, .
(MDI). TFontCharset Charset . :
. File\New\Other\ Pro 0 ANSI, 204 ,
ject\MDI Application. :
1) , ; TColor Color .
2) ( ), , ,
. 0x00FF0000
, 0x0000FF00
.
0x000000FF . 0
Project Manager , MDI App , 0x00FFFFFF
lication, TMemo, int Height
. Font.Height = )Font.Size * Font.PixelsPerInch / 72
. int Pitch
. : int Size
void __fastcall TMainForm::CreateMDIChild(String Name){ Font.Size = )Font.Height * 72 / Font.PixelsPerInch
TMDIChild *Child; AnsiString Name ,
MS Sans Serif
// create a new MDI child window TFontStyles Style :
Child = new TMDIChild(Application);
Child->Caption = Name;
fsBold ;
if (FileExists (Name)) fsItalic ;
Child->Memo1->Lines->LoadFromFile(Name); fsUnderline ;
} fsStrikeOut
void __fastcall TMainForm::FileNew1Execute(TObject *Sender){
CreateMDIChild("NONAME" + IntToStr(MDIChildCount + 1)); void Assign(TPersistent* Source),
} , :
// TFont* Temp = new TFont();
Temp->Assign(Canvas->Font);
void __fastcall TMainForm::FileOpen1Execute(TObject *Sender){
if (OpenDialog->Execute())
// - , ...
CreateMDIChild(OpenDialog->FileName);
}
Canvas->Font->Assign(Temp); //
delete Temp;
.
92 1. 1.4. VCL 93
TPen TCanvas
TPen ,
TCanvas, , . , TFont, TPen TBrush,
. , , ,
.
1.4.41. TPen
1.4.43. TCanvas
TColor Color . , )
, . TRect ClipRect
0x00FF0000 , TFont* Font TCanvas
0x0000FF00 0x000000FF . 0 int TextFlags ,
, 0x00FFFFFF TCanvas
TPenMode Mode . TPen* Pen
enum TPenMode {pmBlack, pmWhite, pmNop, pmNot, pmCopy, TPoint PenPos
pmNotCopy, pmMergePenNot, pmMaskPenNot, pmMergeNotPen,
pmMaskNotPen, pmMerge, pmNotMerge, pmMask, pmNotMask,
TBrush* Brush
pmXor, pmNotXor}
TColor Pixels[int X][int Y] (X,Y)
TPenStyle Style .
enum TPenStyle {psSolid, psDash, psDot, psDashDot,
psDashDotDot, psClear, psInsideFrame} 1.4.44. TCanvas
int Width
MoveTo(int X, int Y) (X,Y)
void Assign(TPersistent* Source), LineTo(int X, int Y) ,
. , (X,Y), Pen
Rectangle(int X1, int Y1, ,
TBrush int X2, int Y2) (X1,Y1))(X2,Y2), Pen.
TBrush . , Rectangle(TRect Rect)
, , (). DrawFocusRect(TRect
, . Rect) Rect
FrameRect(TRect Rect) Rect,
1.4.42. TBrush Pen
FillRect(TRect Rect) , )
Rect, ( Brush)
TColor Color . ) RoundRect(int X1, int Y1, (X1,Y1))(X2,Y2)
, , ) int X2, int Y2, int X3, int Y3) , Pen
. 0x00FF0000 Brush.
, 0x0000FF00 0x000000FF . X3 Y3
0 , 0x00FFFFFF FloodFill(int X, int Y, , (X, Y).
TBrushStyle Style Bitmap, TColor Color, TFillStyle FillStyle fsSurface ,
. FillStyle) () , Color,
enum TBrushStyle {bsSolid, bsClear, bsHorizontal, bsVertical, ,
bsFDiagonal, bsBDiagonal, bsCross, bsDiagCross} fsBorder ,
TBitmap* Bitmap . 88 ,
, Color
88. , TBrush
Ellipse(int X1, int Y1,
int X2, int Y2) (X1,Y1))(X2,Y2)
94 1. 1.4. VCL 95
, ,
TMenuItem, Events, OnClick
( ). . ,
:
1.4.46. TMenuItem void __fastcall TForm1::MyMenu1Click(TObject *Sender)
{
MessageBox (0, " ", " ", mb_OK);
AnsiString Caption . }
), . . OnClick
TBitmap* Bitmap
Close:
. ( )
void __fastcall TForm1::MyMenu10Click(TObject *Sender)
{
bool AutoCheck , ) Close();
hecked };
bool Checked True,
int Count , TPopupMenu
( )
TPopupMenu
bool Default ,
TMainMenu. unu
bool RadioItem , , innu.
Grouplndex. ,
True ,
Checked. .
( PopupMenu),
Byte Grouplndex .
(. Radioltem) , , , (TMenuItem)
TMenuItem* Items[int Index] TPopupMenu TMainMenu.
int Menulndex Items TTimer
.
1.4.47. TMenuItem MS Windows,
WM_TIMER.
Add(TMenuItem* Item) Item
1.4.48. TTimer
Clear() ,
Items
Delete(int Index) Index bool Enabled / ,
TMenuItem* Find(AnsiString ACaption) Word Interval ,
Insert(int Index, TMenuItem* Item) , .. 1000
Remove(TMenuItem* Item) OnTimer
TOpenDialog TSaveDialog ). , ,
:
, . void func(int userValue){ // ,
if ((userValue < 0) || userValue > 10)
, .
throw EIntegerRange(0, 10, userValue);
}
1.4.49. TOpenDialog TSaveDialog
.
,
AnsiString Filter try. try catch,
) . . ,
: , catch
; ,
(...):
| .
, Delphi projects|*.dpr All graphics files| //
*.bmp,*.ico,*.wmf Delphi projects|*.dpr|Bitmap files| int main(void) {
try{
*.bmp.
func();
int FilterIndex ,
};
// EIntegerRange
AnsiString InitialDir , , catch (const EIntegerRange &ERange){
, //
};
AnsiString DefaultExt , , catch ( ... ){ //
bmp return 1;
AnsiString Title };
AnsiString FileName };
TFileEditStyle , (fsEdit) :
FileEditStyle (fsComboBox) try { //
TOpenOptions Options . AnyNumber = StrToInt(Edit1->Text);
TOpenDialog TSaveDialog . };
. C++Builder catch ( ... ) {//
TStrings* Files ofAllowMultiSelect, AnyNumber = 0;
};
, , , . . Memo, Align
, : alClient;
1) 4)
y = a sin(b x2 + c x + d) (e x2 + f x + g), ScrollBar Standard PaintBox
System. ScrollBar,
a, b, c, d, e, f, g , ,
. Kind sbVertical,
x; .
2) , ,
; ScrollBar
3) . , PaintBox ,
,
, .
, ,
. ,
.
2. . ,
. Anchors
File\New\Application,
false akLeft, true
akRight, akTop akBottom. Anchors
C++ Builder.
false akTop, true.
,
PaintBox true Anchors;
, :
5)
1) Caption ;
2) Name MainForm, PageControl,
. , File\Save All;
6) , Run\Run. ,
, File\Save Project As...
.
3. .
, : , , , ,
1) MainMenu Standard ( . .
), . 4. . ,
; , Edit
2) PageControl c Win32. Align , ,
alClient, . , .
PageControl New Page, ,
TabSheet. Caption . . ,
TabSheet ; ,
3) , , Memo1
. Panel Standard, ( Name) ResultMemo . .
Align alRight, Caption , Edit65, Edit215,
( ). , Edit84, Button12, Button19, Button54 . .
. ,
Label Edit. Label ,
Edit. Caption . :
: A =, B =, ..., G =, Xmin =, Xmax = A[], Xmin, Xmax, F[],
N =. Button Caption N Res. ,
. TabSheet Unit1.h , :
102 1. 1.5. 103
" 2 1000.", 5. .
mtError, TMsgDlgButtons() << mbOK, 0); , .
return;
} MainMenu1, . ,
... .
} OnClick. ,
. :
Memo: void __fastcall TMainForm::N5Click(TObject *Sender)
// {
Res.Length = N; // Close();
for (int i=0; i<N; i++){ }
double x = Xmin + (Xmax-Xmin)*i/(N-1); // X , ,
Res[i] = A[0]*sin(A[1]*x*x + A[2]*x + A[3])*(A[4]*x*x + OnClick , ,
A[5]*x + A[6]);
} Button1Click.
, .
// .
Memo1->Clear();
SaveDialog c Dialogs .
Memo1->Lines->Add(":"); :
Memo1->Lines->Add("y = "+FloatToStr(A[1])+"*sin("+FloatToStr(A[2])+ void __fastcall TMainForm::N3Click(TObject *Sender)
"*x*x + "+FloatToStr(A[3])+"*x + {
"+FloatToStr(A[4])+")*("+FloatToStr(A[5])+ if (SaveDialog1->Execute())
"*x*x + "+FloatToStr(A[6])+ Memo1->Lines->SaveToFile(SaveDialog1->FileName);
"*x + "+FloatToStr(A[7])+")"); }
Memo1->Lines->Add("");
Memo1->Lines->Add(" :"); . .
Memo1->Lines->Add("["+FloatToStr(Xmin)+", "+FloatToStr(Xmax)+"]"); 6. . ,
Memo1->Lines->Add(""); , . ,
Memo1->Lines->Add(" ");
Res[], PaintBox
for (int i=0; i<N; i++) ScrollBar.
Memo1->Lines->Add(IntToStr(i)+" -> "+FloatToStr(Res[i])); , ,
, (
, Res[]).
, : . ,
:
.
y = 1*sin(1*x*x + 1*x + 1)*(1*x*x + 1*x + 1) (0, 0) ,
,
: . .
[1, 2]
.
,
0 -> 0.423360024179602 ,
1 -> -0.678077345661505 , (30,20) (200, 100) (
2 -> -2.01922246069815
3 -> -3.39007731922228 ).
4 -> -4.45642014129737
5 -> -4.80433351393652 ,
6 -> -4.04958922519895
7 -> -2.0078214548233
. ,
8 -> 1.11530779307153 () .
9 -> 4.59890619103152 ,
106 1. 1.5. 107
, ,
, , .
/ . .
, .
, [Xmin, Ymin][ Xmax, , , :
Ymax]. Dx = [Xmin, Xmax], Dy = int GetX(double mX, double mXmin, double mXmax, int Xmin, int Xmax,
= [Ymin, Ymax]. int Xi, int kx){
kx ky, return floor(1.0*kx*(Xmax-Xmin)*(mX-mXmin)/(mXmax-mXmin)+Xmin) - Xi;
kx*(XmaxXmin) }
ky*(YmaxYmin). , int GetY(double mY, double mYmin, double mYmax, int Ymin, int Ymax,
DxDy . int Yi, int ky){
(Xi, Yi) return floor(1.0*ky*(Ymax-Ymin)*(mYmax-mY)/(mYmax-mYmin)+Ymin) - Yi;
, }
Nx Ny. , PaintBox.
, Events
(Xi, Yi) XmaxXmin YmaxYmin, OnPaint :
Xi 0 Nx, Yi void __fastcall TMainForm::PaintBox1Paint(TObject *Sender)
0 Ny, {
[Xmin, Ymin][ Xmax, Ymax] . if (Res.Length>1){ // , Res
// PaintBox
int Xmin = PaintBox1->ClientRect.Left;
, (X, Y) int Xmax = PaintBox1->ClientRect.Right;
(X, Y) . : int Ymin = PaintBox1->ClientRect.Top;
int Ymax = PaintBox1->ClientRect.Bottom;
// ,
//
int kx = 2;
int ky = 2;
//
kx, ky, Nx, Ny N Nx = (kx 1)(Xmax Xmin), Ny = (ky 1)(Ymax Ymin). int Nx = (kx-1)*(Xmax-Xmin);
int Ny = (ky-1)*(Ymax-Ymin);
,
. ScrollBar2->Max = Nx;
ScrollBar1->Max = Ny;
// Res ,
double mXmin = Res.Low;
double mXmax = Res.High;
// , mYmin=mYmax,
if (mYmin>=mYmax){
.1.5.1. mYmin = mYmin - 1;
108 1.
mYmax = mYmax + 1;
}
//
int Xi = ScrollBar2->Position;
int Yi = ScrollBar1->Position;
//
PaintBox1->Canvas->MoveTo(GetX(mXmin, mXmin, mXmax, Xmin, Xmax,
2.
Xi, kx), GetY(Res[0], mYmin, mYmax, Ymin, Ymax, Yi, ky));
//
MATLAB
for (int i=1; i<Res.Length; i++)
MATLAB ,
PaintBox1->Canvas->LineTo(GetX(i, mXmin, mXmax, Xmin, Xmax,
Xi, kx), GetY(Res[i], mYmin, mYmax, Ymin, Ymax, Yi, ky)); . MATLAB matrix
}; laboratory ( ).
. MATLAB
}
, : . MATLAB
. ScrollBar , ,
: , ,
void __fastcall TMainForm::ScrollBar1Change(TObject *Sender) .
{
PaintBox1->Refresh();
MATLAB 6.0, 6.5 7.01.
} 6.5.
. , MATLAB
Run\Run. , ,
Help MATLAB
MATLAB, ., , [1], [2], [4], [5], [8], [9] [13]. Internet
1.6. [15] [16].
,
, C++ Builder, 2.1.
.
. . MATLAB
, MATLAB 70 .
C++ . MATLAB
C++ Builder, ,
, .
. , .
,
.
MATLAB ,
,
. MATLAB:
, , ,
, , .
MATLAB
110 2. MATLAB 2.1. 111
(Command History). ,
, .
,
. MATLAB ,
diary.
(Current Directory). ,
, ,
.
Current Directory .
.
, , .
Start (Launch Pad).
Start ,
. (Launch Pad)
, . . 2.1.3.
. 2.1.1. MATLAB
. ,
MATLAB, Save
Workspace As File, save.
MAT. MAT,
Import Data File.
.
, .
, ,
.
. 2.1.3. Start
(Help). MATLAB
,
, MATLAB.
html,
MATLAB, .
. 2.1.2. MATLAB
114 2. MATLAB 2.1. 115
2.1.6. MATLAB
MATLAB .
numeric array MATLAB . ,
, .
2.1.5. / double logical , .
118 2. MATLAB 2.1. 119
, uint32 32 (4
. ). 0 4 294 967 295;
, uint64 64 (8
. . ). 0
logical. . 18 446 744 073 709 551 615.
true false, 1 () , ,
0 () . . , .
MATLAB (, >, ~ =) int* ,
. ,
.
x = magic(4) > 10
44 , ix = int*(x). x ,
magic(4) 10 . double. x ,
char. ( 2 ). .
. 1n :
. mn , y = uint8(magic(3)) % uint8
.
. single.
, (8 ). single .
(4
x='!'
) , (8
numeric.
), . ,
(single),
(double), (int8, , int64) (uint8, , , single.
, uint64), 8, 16, 32, 64 . single.
MATLAB : B = single(A).
MATLAB ; double.
(16 ). MATLAB.
, , .
double. , cell array.
int*. : / .
int8 8 (1 ). , MATLAB .
128 127; .
int16 16 (2 , structure.
). 32 768 32 767; .
int32 32 (4 , . ,
). 2 147 483 648 .
2 147 483 647; . .
int64 64 (8 ). , function handle. (
9 223 372 036 854 775 808 ) ,
9 223 372 036 854 775 807. ,
uint*. : (evaluate). ,
uint8 8 (1 ). . feval
0 255; , .
uint16 16 (2 sin:
). 0 65 535; z=functions(@sin) % 1--1
120 2. MATLAB 2.2. MATLAB 121
z = 1.
function: 'sin'
, ,
type: 'simple'
file: 'MATLAB built-in function' ...:
MATLAB . x=magic(3)+magic(3)^2+magic(3)^3+...
+magic(3)^4
(user classes) MATLAB . MATLAB
Java, 2.
Java Java .
. Java MATLAB. , .
, MATLAB. MATLAB
, , double, 16 .
, . .
format. , format
2.2. MATLAB , MATLAB
. format type type.
, MATLAB: type:
, short ( ). ( )
, . 1000, 4 , x = 112.1416.
1000, short e.
2.2.1. MATLAB 9 ;
MATLAB short e 5 .
MATLAB (. . 2.1.1). , x = 1.1214e+002. 9 ;
. MATLAB (session). long , 16 . ( ) 100,
. 14 15 , = 23.14069263277927.
. , 100, long e.
>> . 9 ;
, , long e 16 .
Enter, . ( ) 10, 15 ,
, = 2.314069263277927e+001. 9 ;
. rat , pi =
1. 3 = 355/113;
x. 3, hex ,
, , . pi = 400921fb54442d18.
MATLAB magic(n). 2.
x=magic(3) :
x =
format long
8 1 6 pi^(exp(1))
3 5 7 ans =
4 9 2 22.45915771836105
( ) 63 . :
round(x) ;
. , , fix(x) ;
_. floor(x) , [x], ,
, +,., *, / . . MATLAB x;
. ceil(x) , x;
122 2. MATLAB 2.2. MATLAB 123
[] , , () mn
. m n,
, m n .
X=[A,B] .
A , :
Y=[C;D] zeros(n,m) nm;
C D. ones(n,m) nm;
5. [] rand(n,m) nm;
horzcat. , V=[A,B] V= eye(n) n;
= horzcat(A,B) . [;] eye(n,m) nm;
vertcat. , magic(n) n.
V=[A;B] V= vertcat(A,B) . MATLAB ,
6. []. ( hilb(n)), (
. hadamard(n)), ( wilkinson(n)),
7. z(n,m) ( hankel(n)).
, z.
, 2.2.3.
(
MATLAB .
).
,
.
. ,
, .
, ,
(:). , p
.
:
, ,
y=A(p,:);
. , A nm,
q sin(A) A.
z=A(:,q); , *.
B=A(:,:); , , , .
. , ,
, ,
. . .
,
A(p,:)=[]; 2.2.1.
nm (s(1), ..., s(n))
(1, ..., n) . A+B plus(A,B)
.
B=[A(s(1),:); A(s(2),:); ... A(s(n),:)]; A-B minus(A,B)
. A*B mtimes(A,B)
A/B (A\B) mrdivide(A,B) ( )
. ,
mldivide(A,B) /= A*inv(B), \B= inv(A)*B (!!
, . , 10 . MATLAB )
10020 . [ ] +, , /, \)
00. , , A ctranspose(A,B)
isempty(A). , A.*B times(A,B) , .* = (aij*bij)
126 2. MATLAB 2.2. MATLAB 127
2.2.1. () 2.2.2. ()
A./B rdivide(A,B) , sum(A) ,
(A.\B) ldivide(A,B) ./ = (aij / bij), .\ = (bij / aij) prod(A) ,
A. transpose(A) ( ) V = diag(A) )
A.^B power(A,B) , aij^bij A = diag(V) V
, , 2* +1 U = triu(A)
2 U = tril(A)
1 . MATLAB , B = orth(A)
Im(A),
V = null(A) V
. Ker(A),
3. =[1,2;3,4] ^2 .^2. p = poly(A)
A^2 J=Jordan(A)
ans =
7 10
15 22 .
. :
A.^2 d=eig(A) ;
ans = [V,D]=eig(A) .
1 4
9 16 V ,
D , .
, MATLAB
, . . ,
, , . S
U V : A=U*S*V1.
S ,
. .
. U, S V svd:
. F=fun(A)
[U,S,V]=svd(A)
F=funm(A,@fun). ,
sin(A) : s=svd(A) .
f=funm(A,@sin)
*t. ,
,
f(x) = ||Ax||2 ||x|| = 1.
:
. ,
expm(A), logm(A), sqrtm(A)
, . 1 2
0 4
2.2.2. 1 4. = *
B =
det(A) 5 8
8 16
B = inv(A)
[n,m] = size(A) 0.7918 20.2082,
S = length(A) , s=max(size(A)) 4.4954 0.8898.
trace(A) , , (rank).
. MATLAB
128 2. MATLAB 2.2. MATLAB 129
, ,
. MATLAB
. .
R=rank(A)
, , x = A\b :
max(size(A))*norm(A)*eps. x =
R=rank(A,tol) -0.5000
0.5000
, , tol.
b=A*x :
(norm).
b =
norm(A) = max(svd(A)). .
0.5000
norm(A,p), p = 1, 2, inf, fro: 0.5000
norm(A,1) = max(sum(abs(A)) 0.0000
; 3. m<n. , ,
norm(A,2) = norm(A)= max(svd(A)) . x0 = A\b x0,
; m .
norm(A,inf) = max(sum(abs(A)) V=null(A) Ker(A).
; x = x0 +V*C,
norm(A, fro) = sqrt(sum(diag(A*A))) , . , C=(C1, ..., Ck).
X : , ,
norm(X,p) = sum(abs(X).^p)^(1/p) 1 p < ; , MATLAB
norm(X)=norm(X,2); :
norm(A,inf) = max(abs(X)) Warning: Rank deficient, rank = 2 tol = 2.1756e-015.
; .
norm(A,inf) = min(abs(X)) MATLAB ,
. , ,
, Help MATLAB MATLAB,
2.2.4. . [1], [2], [4], [5], [8], [9] [13].
m n . MATLAB.
. Symbolic Math
Symbolic Math
A*x = b. mn. . Maple.
1. m=n. . , Extended Symbolic Math Toolbox, Symbolic Math Toolbox,
: Maple
x = A\b; Maple.
inv(A) help symbolic .
pinv(A), x = pinv(A)*b. Maple mfunlist.
pinv(A) inv(A) (. mhelp <func
pinv). tion>. funtool
2. m>n. , , .
. . x = A\b x,
|| A*xb ||2. , , . sym. ,
4. (, ) :
130 2. MATLAB 2.2. MATLAB 131
% :
% Nes_4.txt
>> help fact2
v=fopen('Nes_4.txt','rt');
FACT2 n!!.
S=fscanf(v,'%g',[1 inf]); % Nes_4.txt
L=length(S); % Fact2(n) n!! n
F=fft(S'); % what m ,
F1=F'; P=F1.*conj(F1)/L; % fact2.m. type fact2
plot(P); axis([0 length(P) min(P) max(P)]); %
fclose(v); % m fact2.m.
: S, L, F, F1 P. 2.2.6.
. % MATLAB *.txt, *.html,
. *.m *.mat.
. MATLAB, fopen. *.txt, *.html, *.m *.mat.
. . :
.
Fid=fopen [ ] [].
:
. Fid .
, . : , . Fid 1,
, 1, .
function y = function_name(u,v,w )
fopen , ,
. . .
lookfor help < >;
;
2.2.3.
,
.
, 'rt' ( )
'wt' , . ,
function, :
,
function [x, y, z] = sphere(theta, phi, rho)
, , 'at' , . ,
m.
8. n!!. , n=2k, n!! 'rt+' . ,
2 2k, n=2k1, n!! ,
'wt+' . ,
1 2k1.
,
function ff = fact2(n)
% FACT2 n!!.
'at+' , ,
% fact2(n) n!! n
r=rem(n,2); % 2
if r==0;
ff = prod(2:2:n); % n filename , MAT
else ff = prod(1:2:n); % n
LAB, .
end
. fopen *.mat,
t.
m, fact2.m . fclose. , fclose(fid)
MATLAB: fid, fclose(all) ) .
fact2(6) fscanf. ,
ans =
48 fopen. :
134 2. MATLAB 2.2. MATLAB 135
S . lower('str'). str
strcmpi , , .
.
strncmp( 'strT , 'str2' ,n). 2.3.5.
n . strncmpi( 'strT , 'str2' ,n) ,
. ,
findstr(strl,str2). double ( ) char.
. num2str(A).
, MATLAB
. : , .
s = 'Find the starting indices of the shorter string.';
title, xlabel. ylabel text;
findstr(s,'the') num2str(A,precision).
ans = , precision. precision
6 30 ;
findstr('the',s)
ans =
num2str(A,format). ,
6 30 format. ,
strjust(S). (
, , ). . :
strjust(S, 'left') , a strjust(S,'center') A=rand(2,3)
A =
. 0.4057 0.9169 0.8936
strmatch( 'str' ,STRS). 0.9355 0.4103 0.0579
STRS , , str = num2str(A,2)
str = % char 2--22
str, . strmatch( 'str' 0.41 0.92 0.89
,STRS, 'exact') STRS, 0.94 0.41 0.058
str. int2str(X). X
strrep(strl,str2,str3). . () . X ,
str2, str1, str3. : ,
s1 = 'This is a good example.'; . X ,
str = strrep(s1,'good','great')
str =
. :
This is a great example. >> int2str(133.3)
ans =
strtok('str',d). . 133
().
char 13.
(ASCII d=9),
mat2str(A). ,
(ASCII d=13) (ASCII d=32).
MATLAB, eval.
[token,rem]=strtok(...). rem
. ,
. :
[ ].
str='This is a good example for me.':
[token,rem] = strtok(str)
mat2str(A,n) ,
token = n . eval(str)
This . :
rem = mat2str(A,3)
is a good example for me. ans =
upper( 'str'). str, [0.406 0.917 0.894;0.935 0.41 0.0579] % char 136
, str2num(s).
. ASCII double. :
142 2. MATLAB 2.4. 143
str2num('3.14159e0') dec2hex(d). d
ans =
,
3.1416
16.
ans double. , hex2dec('hex_value').
+ . MathWorks hex_value ( 09 AF) ()
str2num double. :
str2double. d = hex2dec('10FE3')
str2double('str'). str, d =
ASCII, . + 69603
. ,
MAT 2.3.7.
LAB .
. ,
,
2.3.6. eval (' '). :
eval('2*sin(pi/3)+(1/3)^(1/5)')
ans =
. . 2.5348
bin2dec('binarystr').
. ,
. :
, :
bin2dec('101')
ans = a=2; b=4;
5 eval('a^2 - sqrt(b) + a*b - a/b')
ans =
dec2bin(d). d ( char) 9.5000
(0 1). d feval (@_,1,2,...)
, , 252 ( ). .
dec2bin(d,n) , , :
n . : feval(@prod,[1 2 3])
dec2bin(111.3,9) ans =
ans = 6
001101111
dec2base(d,base). d 2.4.
, base.
, ,
base 2 36.
, .
dec2base(d,base,n) , d
.
base, n .
, ,
:
, (. 2.4.1).
dec2base(365,21,5) .
ans =
000H8 :
{}, cell ;
base2dec(S, ). S,
cellstr ;
,
cellfun ;
double. :
celldisp ;
d = base2dec('4D2',16)
d =
cellplot ;
1234 deal ;
144 2. MATLAB 2.4. 145
num2cel ; . , ,
cell2mat ; .
mat2cell ; .
cell2struct ;
struct2cell ; .
iscell , . , .
3.
2.4.1. A{1, 1} = [1 4 3; 0 5 8];
A{1, 2} = '';
{} cell A{2, 1} = 3+7i;
. {} A{2, 2} = -2:2:6
[] . . A =
[2x3 double] ''
1. :
[3.0000+ 7.0000i] [1x5 double]
C = {1 2 3 4}
C = [1] [2] [3] [4] 2. MATLAB
.
C(j) .
. .
C{j} .
3. ,
C{1}, C{2}, C{3}, C{4} .
, .
: MATLAB . ,
A = [C{:}] ,
A = 1 2 3 4
(. ).
celldisp:
. , celldisp(A)
22 : A{1,1} =
B=[{''}, {''};{''},{''}] 1 4 3
B = 0 5 8
'' '' A{2, 1} = 3.0000+ 7.0000i
'' '' A{1,2} =
A{2, 2} = -2 0 2 4 6
, .
MATLAB .
. cellplot:
( ). cellplot(A)
{ }.
2. 22,
, , .
A(1, 1) = {[1 4 3; 0 5 8]};
A(1, 2) = {''};
A(2, 1) = {3+7i};
A(2, 2) = {-2:2:6}
A =
[2x3 double] ''
[3.0000+ 7.0000i] [1x5 double]
1. { } ,
[ ] . { }
, [ ] . 2.4.1. 2))2
146 2. MATLAB 2.4. 147
, , ,
, MATLAB . MATLAB
. , , .
. 6. , .
cell. cell C(1) = {[1 2 3]}; C(2) = {[4 5 6]}; C(3) = {[7 8 9]};
, . , :
2 3 : C{1:3}
B = cell(2, 3) ans =
1 2 3
, . ans =
4 5 6
ans =
2.4.2. 7 8 9
: ,
, ; :
, . B = [C{1}; C{2}; C{3}]
B =
. 1 2 3
, . 4 5 6
7 8 9
,
, ,
. , .
, .
4. 2 2, .
,
, A{1, 2}, :
[D{1:2}] = eig(B)
c = A{1, 2} D =
c = % char [3x3 double] [3x3 double]
5. (2,2) ,
A{1,1}: eig, .
d = A{1, 1}(2, 2)
d = 5 , D{1} D{2} .
. D{1}
ans =
( ), -0.2320 -0.7858 0.4082
. . , -0.5253 -0.0868 -0.8165
: -0.8187 0.6123 0.4082
D{2}
B=A(1,:) ans =
B = 16.1168 0 0
[2x3 double] '' 0 -1.1168 0
. 0 0 -0.0000
, . ,
: 2.4.3.
A(1, :)=[] ,
A = . , , .
[3.0000+ 7.0000i] [1x5 double]
. , cell .
A(2)=[] ,
. .
148 2. MATLAB 2.4. 149
.
, . , .
clear A .
A(1, 1) = {magic(5)}; , .
A(1, 2) = {{[5 2 8; 7 3 0; 6 7 3] 'Test 1'; [2-4i 5+7i] {17 []}}} , ,
cellplot(A)
, .
, A 3 :
55 (1,1)
A{1, 1};
2 2 (1, 2)
A{1, 2};
3 3 (1, 1)
(1, 2) A{1, 2}{1, 1};
(2, 2)
A{1, 2}{1, 1}(2, 2);
(1, 2) (2, 2),
(1, 2), A{1,2}{2,2}{1,2}.
2.4.4. ,
,
. .
. 2.4.2. 7.
cel_str = cell(1,2)
cel_str{1}.label = '19.09.05';
,
cel_str{2}.xdat = [-0.03 0.41 1.98 2.12 17.11];
3 : A(1, 2) A, cel_str{2}.ydat = [-3 5 8 0 9];
2 2, , , celldisp(c_str)
{17 [ ]}. cel_str{1} =
label: '19.09.05'
cell. cel_str{2} =
cell : xdat: [-0.0300 0.4100 1.9800 2.1200 17.1100]
1. 1 2: ydat: [-3 5 8 0 9]
A = cell(1, 2); {1} cel_str label ,
2. A(1, 2) 2 2 A: {2} .
A(1, 2) = {cell(2, 2)};
, ,
3. A, ,
cell_array{index}.field
:
A(1, 1) = {magic(5)};
A{1, 2}(1, 1) = {[5 2 8; 7 3 0; 6 7 3]}; . , label {1}
A{1, 2}(1, 2) = {'Test 1'}; , cel_str{1}.label.
A{1, 2}(2, 1) = {[2-4i 5+7i]};
A{1, 2}(2, 2) = {cell(1,2)}
A{1, 2}{2, 2}(1) = {17}; 2.4.5.
. , cat. , C
. 222, A B:
150 2. MATLAB 2.5. 151
A{1, 1} = 'Name'; :
A{1, 2} = [4 2; 1 5];
>> summer
A{2, 1} = 2-4i;
summer =
A{2, 2} = 7;
image: 'image1'
B{1, 1} = 'Name2';
description: ' '
B{1, 2} = [ 3 5 ];
date: [1x1 struct]
B{2, 1} = 0:1:3;
B{2, 2} = 3; , summer .
C = cat(3, A, B); , .
2. summer.
2.5. summer(2).image = 'image2';
summer(2).description = ' ';
, summer(2).date.year = 2005;
. summer(2).date.month = 07;
. MATLAB : summer(2).date.day = 22;
struct ; summer 12. ,
fieldnames ; , ,
getfield ; :
setfield ; >> summer
rmfield ; summer =
1x2 struct array with fields:
isfield , ;
image
isstruct , ; description
struct2cel . date
field
2.5.1. names, , .
MATLAB
.
struct.
.
. . summer description
11, . , image
C MATLAB . . .
1. , . struct. struct :
summer 11 : str_array = struct('<_1>','<>',
, . MATLAB '<_2>','<>', ...).
: 3. struct, summer
summer.image = 'image1'; 11, :
summer.description = ' ';
summer.date.year = 2005; summer = struct('image', 'image2', 'description', ' ', 'date',
summer.date.month = 07; struct('year', 2005, 'month',07, 'day', 22))
summer.date.day = 20; summer =
A(1).nest.xdata = [4 2 8];
A(1).nest.ydata = [7 1 6]; 2.6.1. ,
A(2).data = [9 3 2; 7 6 5];
A(2).nest.testnum = 'Test 2';
, MATLAB, M.
A(2).nest.xdata = [3 4 2]; M (/
A(2).nest.ydata = [5 0 9] MATLAB). M: (m )
A = .
1x2 struct array with fields:
data
MATLAB
nest .
.
. .
. MATLAB,
, (.). . ,
, . ,
, . , :
A 2 : .
A(1) , . :
A(1).nest; function y = function_name(u,v,w )
xdata A(1) .
A(2).nest.xdata; lookfor help < >;
2 ydata .
A(1) A(1).nest.ydata(2). help < >.
2.4.3. , ;
,
.
. ,
, , function, :
cat.
function [x, y, z] = sphere(theta, phi, rho)
8. 122
( ), . ,
: .
, , m.
summer(1,2,2).image = 'image4';
summer(1,2,2).description = ' '; . M
summer(1,2,2).date.year = 2005; . ,
summer(1,2,2).date.month = 07; M. ,
summer(1,2,2).date.day = 24;
.
.
, . ,
. .
1.
2.6. MATLAB u, n = length(u)
avg = mean(u,n) med = median(u,n).
function [avg,med] = newstats(u) % Primary function
, ,
% NEWSTATS Find mean and median with internal functions.
. n = length(u);
156 2. MATLAB 2.6. MATLAB 157
, . MATLAB
lotka.m ( ), , ,
. . , ,
global ALPHA BETA MATLAB ,
ALPHA = 0.01; .
BETA = 0.02; .
[t,y] = ode23('lotka',[0 10],[1; 1]);
plot(t,y)
. MATLAB
.
global ALPHA BETA ,
, lotka.m. , 2.6.1.
,
lotka.m. :
< lt() A<B; lt(A,B);
,
<= le() A<=B; le(A,B);
. > gt() A>B; gt(A,B);
, >= ge() A>=B; ge(A,B);
; == eq() A==B; eq(A,B);
global ~= ne() A~=B; ne(A,B);
; global M.
.
2.6.2. MATLAB , ,
MATLAB : . MATLAB
. . , ,
; 1, 0.
. ;
. .
if, for, while, switch.
, ,
. , .
. , , . MATLAB
( ), ( ), . . 2.6.2
( ), ( ):
(:). A = [0 1 1 0 1];
. B = [1 1 0 0 1];
. (.'),
(.^), ('), (^). 2.6.2.
. (+) (-).
. (.*), (./), & and() , A & B = 01001
(.\), (*), 1 , )
(/), (\). true
( ) 0
. (+) (-) .
. (:). | or() 1 ) A | B = 11101
, )
. true ( )
. 0
162 2. MATLAB 2.6. MATLAB 163
2.6.2. any. 1,
; 0. any
~ not()
.
, A ~A = 10010 isnan isinf. 1 NaN Inf .
xor 1 ) isfinite , inf NaN.
, find. ,
true ( ) 0 . ,
xor(A,B)=10100 .
= find( <> )
, .
. 5. 100
, , , 6.
. MATLAB >> A = magic(3)
. , , 1, A =
0. 8 1 6
3 5 7
, 4 9 2
(shortcircuit). >> i = find(A > 6);
, . A(i) = 100
A =
100 1 6
2.6.3. 3 5 100
4 100 2
try...catch 7. .
; 2.
return . if rem(a,2) == 0
disp('a is even')
end,
b = a/2;
, . else
if...else...elseif...end. . disp('a is odd')
: b = (a+1)/2;
end
if _
switch...case...otherwise...end. .
end switch expression (scalar or string)
: case value1
statements % Executes if expression is value1
if _ case value2
statements % Executes if expression is value2
else .
.
end .
: otherwise
statements % Executes if expression does not
if _
% does not match any case
end
elsif _
. switch ... case 1 ... case k ... otherwise
else ... end
end . :
. if ... end switch, (
);
. , MATLAB case.
if end, case, ,
end. , MATLAB . ,
if end end. .
if ... else ... end if ... elseif ... , case
else ... end. . otherwise. switch ;
if , otherwise. otherwise,
. , ,
else . , case;
, , if ( , elseif ) . end .
elseif , , switch ,
if ( , elseif) . , case. case ,
elseif, , strcmp(, ) .
. elseif 8. n!!. , n=2k, n!!
if. 2 2k, n=2k1, n!!
6. . 1 2k1.. rem(n,2) n
2. 2. ( =0), .
if rem(a,2) == 0 ( =1), .
disp('a is even')
b = a/2; function ff = fact2(n)
end % FACT2 n!!.
166 2. MATLAB 2.6. MATLAB 167
% fact2(n) n!! n
switch rem(n,2) 2.6.4.
case 0
ff = prod(2:2:n); MATLAB .
case 1 ,
ff = prod(1:2:n); .
otherwise
end eval. .
otherwise.
eval('string')
, .
while...end. : . eval('string')
while expression string, ,
statements , . , t,
end format rational
. while ... eval('t = clock')
end , t =
2005 9 21 17 16 1983/40
. ,
. 10.
any all. n:
9. t = '1/(i + j-1)';
n, n! , 100 : n = 4;
for i = 1:n
n = 1;
for j = 1:n
while prod(1:n) < 1e100
G(i,j) = eval(t);
n = n + 1;
end
end
end
while break. format rational
while , G
. G =
1 1/2 1/3 1/4
for...end. : 1/2 1/3 1/4 1/5
for index = start:increment:end 1/3 1/4 1/5 1/6
statements 1/4 1/5 1/6 1/7
end feval. . :
. for .... end [y1,y2...] = feval(function,x1,...,xn)
. 1.
function , (m), feval(function,
, .
x1,...,xn) .
,
function .
; ,
, . , .
, : [V,D] = eig(A)
[V,D] = feval(@eig,A)
for i = 1:m
for j = 1:n 11. fun.
A(i,j) = 1/(i + j - 1); x,
end .
end
fun = [@sin; @cos; @log];
for , k = input('Choose function number: ');
, x = input('Enter value: ');
for p=[5,6,9,10,17,18,16]; feval(fun(k),x)
168 2. MATLAB 2.6. MATLAB 169
2.6.5. warning,
:
, , warning('<_>')
, .
,
.
2.6.6. ,
. ,
, . . MATLAB ,
MATLAB . ,
. , .
, .
, try catch, for while .
. M.
trycatch , 12. 1001
: [0 10] :
function matrix_multiply(A,B) i = 0;
try for t = 0:.01:10
X = A*B i = i + 1;
catch y(i) = sin(t);
disp '** Error multiplying A*B' end
end
trycatch . try,
t = 0:.01:10;
catch. end. y = sin(t);
try ,
,
. , MATLAB
MATLAB .
try catch .
, tic toc.
catch .
. MATLAB
. ,
, , .
.
catch.
trycatch, .
. ,
( ),
:
try.
y = zeros(1, 100)
try
for i = 1:100
statement1
y(i) = det(X^i);
catch
end
try
statement2
catch . MATLAB
disp 'Operation failed'
end
end .
lasterror ,
.
MATLAB , .
, . , .
170 2. MATLAB
.
, .
MATLAB :
clear ;
pack ;
quit MATLAB 3.
;
save . MATLAB C
load . , <math.h> C/C++
. ( 20 )
: . C MATLAB (
, CML)
, ; ( 400) .
( .dll)
, clear ; C.
. MATLAB MATLAB.
.
. MATLAB MATLAB
. , .
, MATLAB MATLAB,
a = 5; ,
global a MATLAB. MATLAB
a , mxArray,
. clear a MATLAB.
MATLAB, . .
clear global a . MATLAB,
, ,
, .
MATLAB ,
. .
3.1.
MATLAB 2.1,
MATLAB 6.0. 2.3
MATLAB 6.5 Compiler,
. MATLAB 7(R14)
.
MATLAB Compiler_40. ,
, (dll),
, 8,7
( mglinstaller.exe)
172 3. 3.1. 173
mlf. mlfCatch /* 8 */
{
mlfPrintf("In catch block: \n");
MATLAB. , MATLAB sin mlfPrintMatrix(mlfLasterr(NULL));
MATLAB mlfSin. mlf }
. mlfEndCatch
mxDestroyArray(factors1); /* 9 */
3.1.5. mxDestroyArray(factors2);
mxDestroyArray(common_factors);
,
, . mlfRestorePreviousContext(0,0); /* 10 */
, C return(EXIT_SUCCESS);
}
. ,
. intro.c :
<matlab>\extern\examples\cmath. 1.
/* intro.c*/ matlab.h, mxArray
#include <stdio.h> .
#include <stdlib.h> 2. MATLAB. (
#include <string.h>
#include "matlab.h" /* 1 */ )
mxArray *,
int main() . (volatile),
{
double num1, num2;
(try block)
mxArray *volatile factors1 = NULL; /* 2 */ .
mxArray *volatile factors2 = NULL; 3. mlfEnterNewContext ()
mxArray *volatile common_factors = NULL; .
mlfEnterNewContext(0,0); /* 3 */ , .
,
printf("Enter a number: "); /* */ .
scanf("%lf", &num1);
printf("Enter a second number: ");
4. (try block)
scanf("%lf", &num2); mlfTry .
5. mlfScalar(),
mlfTry /* 4 */
mxArray, .
{
mlfAssign(&factors1, mlfFactor(mlfScalar(num1))); /* 5 */ , ,
mlfAssign(&factors2, mlfFactor(mlfScalar(num2))); mlfScalar() mlfFactor().
mlfAssign(&common_factors, /* 6 */
mlfIntersect(NULL, NULL, factors1, factors2, NULL)); mlfFactor(). mlfFactor()
, , mlfFactor(),
if (mlfTobool(mlfIsempty(common_factors))) /* 7 */ factors1, mlfAssign(). ,
printf("%0.0lf and %0.0lf are relatively prime\n",
num1, num2);
, ,
else mxDestroyArray(). ,
{ , ,
printf("%0.0lf and %0.0lf share common factor(s):", .
num1, num2);
mlfPrintMatrix(common_factors); 6. mlfIntersect()
} , ,
} /* end mlfTry */ .
178 3. 3.1. 179
. , .
NULL . . C.
7. mlfIsempty() , mbuild :
1 (), , 0 ;
(), . , mlfIsempty() (User Profiles);
MATLAB mxArray , <matlab>\bin.
if. mbuild .
mlfTobool(), , mbuild C
C. . ,
8. mlfCatch catch .
. mlfEndCatch catch. Windows ,
. catch MATLAB,
mlfLasterr(), . mbuild
, . compopts.bat, setup
9. MATLAB, Application Data\MathWorks\
mlfAssign(). MATLAB\R12. Windows NT Windows 95/98/2000
, . , <windir>\Profiles\username.
, mlfScalar(), mbuild , C C++,
. , factors1 factors2, : .c C .cpp, .cxx, .cc C++.
. C
10. . C. C mbuild
, mlfRestorePreviousContext(). .
1. Windows C
. . ( DOS MATLAB):
CD\Glava_5\Pr_5_04_3_C_Sh_Lib_BB mbuild filename.c
Project1.cpp Borland C++ Builder, , C, mbuild
MATLAB .
. . , Bor
land Microsoft Visual C/C++
3.1.6. mbuild filename.c
, :
C, mbuild has detected the following compilers on your machine:
( MATLAB) C.
. [1] : Borland compiler in T:\Borland\BC.500
. [2] : MSVC compiler in T:\DevStudio\c.106
, , [0] : None
.
MathWorks mbuild, . Please select a compiler. This compiler will become the default:
mbuild : , Enter.
.
; C
. mbuild -setup
180 3. 3.1. 181
. setup mbuild , ,
. setup DLLs, ( PATH).
intro.exe .
compopts.bat. , :
. . 3.1.3 Enter a number: 333
, MATLAB C Math Library.
, mbuild Enter a second number: 444
333 and 444 share common factor(s): 3 37
, v
mbuild-v filename1 [filename2 ...] .
,
,
mbuild. MATLAB C, MathWorks
2. , MATLAB.
compopts.bat, mbuild -setup. , ,
:
mbuild -setup, . c, , bin, mbuild
<matlab>\bin\win32\mbuild. , ;
c MEX, ;
3.1.3. PC MATLAB (dll),
.
Borland C/C++, Version 5.0 bcccompp.bat
Borland C/C++, Version 5.2 bcc52compp.bat MATLAB,
Borland C++Builder 3.0 bcc53compp.bat , mglinstaller.exe
Borland C++Builder 4.0 bcc54compp.bat <matlab>\extern\lib\win32\.
Borland C++Builder 5.0 bcc55compp.bat .
Lcc 2.4 (bundled with MATLAB) lcccompp.bat
Microsoft Visual C/C++, Version 5.0 msvc50compp.bat MATLAB mglinstaller.exe.
Microsoft Visual C/C++, Version 6.0 msvc60compp.bat , bin\win32
(PATH). , <applic>,
C, f : applic \bin\win32.
mbuild -f <file> ... MATLAB, ,
f mbuild, <file>. . ,
<file> , <file> .
. UNIX .
mbuild, ,
. bin/$ARCH LD_LIBRARY_PATH. ,
mbuild , , Linux,
. mgl_runtime_dir, mgl_runtime_dir/bin/glnx86
mbuild 5, MATLAB. LD_LIBRARY_PATH.
. , .
, DOS, :
DOS : The ordinal #### could not be located in the dynamic-link library
mbuild intro.c dforrt.dll.
intro.exe. 32 Micro ,
soft Windows . dforrt.dll dformd.dll Windows
182 3. 3.2. mxArray 183
<matlab>\bin\win32, , 1. , .
. MATLAB .
UNIX. 2. , ,
UNIX , .
Help MATLAB. , 3. .
MATLAB: $HOME/.matlab/R12/mbuildopts.sh <matlab>/bin/ 4. . MAT
mbuildopts.sh. mbuild UNIX PC . LAB, .
UNIX C/C++ 5. . ,
(*.so) (*.sl). . , ,
.
C/C++ (SHLIB_PATH, LIBPATH, LD_LIBRARY_PATH).
1. int*
.
.
, API C
MATLAB C.
.
UNIX . mxArray MATLAB.
,
3.1.4. UNIX , ( ) ()
.
. mlf mx.
HP700 setenv SHLIB_PATH
<matlab>/extern/lib/hp700:<matlab>/bin/
hp700:$SHLIB_PATH 3.2.2.
IBM RS/6000 setenv LIBPATH
<matlab>/extern/lib/ibm_rs:<matlab>/bin/ibm_rs:$LIBPATH
setenv LD_LIBRARY_PATH . MAT
<matlab>/extern/lib/<arch>:<matlab>/bin/ LAB.
<arch>:$LD_LIBRARY_PATH . , , .
.
, mbuild UNIX :
Windows, . Help MATLAB. ;
;
3.2. mxArray ;
, .
MATLAB mxArray. ,
, , C , , ,
MATLAB . , .
mxArray, , ,
, . .
. . MATLAB C
, MATLAB, Math Library Reference.
(. 2 Help/Using MATLAB).
3.2.1.
3.2.1. MATLAB
MATLAB mlfScalar() 1))1 ()
MATLAB: mlfColon() 1))n ()
184 3. 3.2. mxArray 185
3.2.1. () .
MATLAB Help mxClass_ID.
mlfDoubleMatrix() m))n () , ndim dims,
mxCreateDoubleMatrix() , mxArray.
mxCreateNumericArray() , (m))n))p) ...) MATLAB API .
int ndim = 3; /* */
mlfHorzcat() int dims[3] = { 3,3,2 }; /* */
mlfVertcat()
mlfOnes() mxArray *A = NULL; /* mxArray */
mlfZeros() , , ,
mlfRand(), mlfRandn() , mlfAssign(&A, mxCreateNumericArray( ndim,
dims,
mlfEye(), mlfMagic()
mxDOUBLE_CLASS,
mxREAL));
. mlfPrintMatrix(A);
, mlfScalar(). mxDestroyArray(A);
3--3--2.
, 11 mxArray, (:,:,1) =
. , 0 0 0
, mlfScalar(). 0 0 0
0 0 0
MATLAB, mlfDoubleMatrix() (:,:,2) =
. , 0 0 0
, 0 0 0
mxArray. 0 0 0
1 1 1 mxArray *C = NULL;
1 1 1
static double data1[] = { 1, 4, 2, 5, 3, 6 };
(),
static double data2[] = { 7, 10, 8, 11, 9, 12 };
, mlfColon().
(:) MATLAB. mlfAssign(&A, mlfDoubleMatrix(2, 3, data1, NULL));
, 1 10. mlfAssign(&B, mlfDoubleMatrix(2, 3, data2, NULL));
mxArray *A = NULL; mlfAssign(&C, mlfCat(mlfScalar(3), A, B, NULL));
mlfAssign(&A, mlfColon(mlfScalar(1),mlfScalar(10),NULL));
mlfPrintMatrix(A); mlfPrintMatrix(C);
mxDestroyArray(A); mxDestroyArray(A);
. mxDestroyArray(B);
mxDestroyArray(C);
1 2 3 4 5 6 7 8 9 10
. :
: (:,:,1) =
1 2 3
mxArray *mlfColon(mxArray *start, mxArray *step, mxArray *end); 4 5 6
, .
(:,:,2) =
7 8 9
. 10 11 12
. ,
.
. MATLAB [], [;],
, ,
.
mlfIndexAssign(). ,
mlfHorzcat() mlfVertcat(),
,
. mlfHorzcat()
mlfVertcat() C. , .
MATLAB: A = [ 1 2 3; 4 5 6 ]. MATLAB, A(2,2) = 17. (?,?)
, C () .
mlfDoubleMatrix(), mlfHorzcat() mlfVertcat(). . 3.4.
mxArray *A = NULL; mxArray *A = NULL;
mlfAssign(&A, mlfVertcat(mlfHorzcat(mlfScalar(1), mlfIndexAssign(&A, "(?,?)", /* */
mlfScalar(2), mlfScalar(2),mlfScalar(2), /* */
mlfScalar(3), mlfScalar(17)); /* */
NULL), mxDestroyArray(A);
mlfHorzcat(mlfScalar(4), A
mlfScalar(5),
. , :
mlfScalar(6),
NULL), 0 0
NULL )); 0 17
.
mlfPrintMatrix(A);
mxDestroyArray(A); , mlfIndexAssign(). ,
, .
mlfVertcat() mlfHorzcat(),
. , MATLAB ,
mlfCat(). mlfCat() mxArray
, . , . API mxGetPr()
.
mxArray *A = NULL; C memcpy(). API mxGetPi(),
mxArray *B = NULL; .
188 3. 3.2. mxArray 189
2. , , , . 3.2.2
, , mxGetPr().
, .
mxArray. , . MATLAB C Math Library Reference.
,
. , 3.2.2.
MATLAB API .
int ndim = 3; mlfSparse()
int dims[3] = {3,3,2};
mlfFull()
int bytes_to_copy = (3 * 3 * 2) * sizeof(double);
double data[] = { 1,4,7,2,5,8,3,6,9,10,13,16,11,14,17,12,15,18}; mlfSpones()
double *pr = NULL; mlfSprand()
mxArray *A = NULL; mlfSprandn()
mlfSprandnsym()
/* create the array */ mlfSpconvert()
mlfAssign(&A ,mxCreateNumericArray( ndim, mlfSpeye()
dims,
mlfSpdiags()
mxDOUBLE_CLASS,
mxREAL));
mlfNnz()
/* get pointer to data in array */ mlfAny() ,
pr = mxGetPr(A); mlfAll()
mlfNzmax() ,
/* copy data to pointer */
memcpy(pr, data, bytes_to_copy); mlfSpfun()
mlfPrintMatrix(A);
mxDestroyArray(A); .
. mlfSparse() .
(:,:,1) = , :
1 2 3 ;
4 5 6 .
7 8 9
(:,:,2) = mlfSparse().
10 11 12 .
13 14 15
16 17 18 99. 81 9
, . 81
,
. ,
C, ,
9 , , .
C MATLAB.
NULL, mlfSparse(),
. .
3.2.3. mxArray *A = NULL;
mxArray *B = NULL;
. /* */
mlfAssign(&A, mlfEye(mlfScalar(9),NULL));
. mlfPrintMatrix(A);
190 3. 3.2. mxArray 191
/* */ (5,5) 5
mlfAssign(&B,mlfSparse(A,NULL,NULL,NULL,NULL,NULL));
mlfPrintMatrix(B); 0 0 0 0 0 0
0 0 0 0 0 0
mxDestroyArray(A); /* */ 0 0 0 5 0 0
mxDestroyArray(B); 0 0 5 0 5 0
0 0 5 0 5 0
. 0 0 0 5 0 0
, , 0 0 0 0 0 0
. mlfSparse() :
, i j, , mlfFull().
; mlfPrintMatrix() ,
, s, , .
. i, j s
;
, m n,
3.2.4.
;
, .
, . .
. .
, ,
, 76
.
. 5
.
,
( ).
.
static double row_subscripts[] = { 3, 4, 5, 4, 5, 6 };
.
static double col_subscripts[] = { 4, 3, 3, 5, 5, 4 };
mxArray *i = NULL; . MATLAB C Math Library Reference.
mxArray *j = NULL;
mxArray *S = NULL; 3.2.3.
mlfAssign(&i, mlfDoubleMatrix(1, 6, row_subscripts, NULL));
mlfAssign(&j, mlfDoubleMatrix(1, 6, col_subscripts, NULL)); mxCreateString()
mlfChar()
mlfAssign(&S, mlfSparse(i, j, /* */
mlfDouble()
mlfScalar(5), /* */
mlfScalar(6), /* */
mlfScalar(7), /* */ mlfStr2mat() ,
NULL)); mlfStrcat()
mlfPrintMatrix(S); mlfStrvcat()
mlfPrintMatrix(mlfFull(S)); mlfCellstr()
mxDestroyArray(i); mlfChar()
mxDestroyArray(j);
mxDestroyArray(S); mlfDeblank()
: .
(4,3) 5 mlfDisp(), mlfPrintMatrix()
(5,3) 5 mlfNum2Str()
(3,4) 5 ,
(6,4) 5 mlfInt2str()
(4,5) 5 mlfStr2num()
192 3. 3.2. mxArray 193
MATLAB. , /* */
mlfSize(mlfVarargout(&D1,&D2,NULL),A,NULL);
,
MATLAB, C /* */
. MATLAB 16 Unicode. mlfFprintf(mlfScalar(1),
MATLAB mxCreateString("Resulting array is %d-by-%d.\n"),
D1, D2, NULL);
API mxCreateString(). mxDestroyArray(A);
C , ( MATLAB mxDestroyArray(D1);
). mxDestroyArray(D2);
mxArray *A = NULL; 29 . my dog
mlfAssign(&A, mxCreateString("my string")); my string:
mlfPrintMatrix(A);
mxDestroyArray(A); my string
my dog
:
mlfStrcat(), mlfStrvcat() mlfStr2mat()
my string
.
. . MATLAB C Math Library
, Reference.
mlfChar(). , ASCII .
"my string", mlfChar() ,
: MATLAB. ,
mxArray *i; , MATLAB. , ,
static double ASCII_codes[] = {109,121,32,115,116,114,105,110,103 };
mlfAssign(&i, mlfDoubleMatrix(1, 9, ASCII_codes, NULL));
, ,
mlfPrintMatrix(mlfChar(i,NULL)); .
mxDestroyArray(A); , mlfDeblank().
: "my dog"
my string A, . B = A(2,:) MATLAB.
B .
, mxArray *B = NULL;
mlfAssign(&B,mlfIndexRef(A,
mlfDouble(). "(?,?)", /* */
. mlfScalar(2), /* */
MATLAB, mlfCreateColonIndex()));
mlfPrintMatrix(mlfSize(NULL,B,NULL));
. ,
mlfPrintMatrix(mlfSize(NULL,mlfDeblank(B),NULL));
, , . mlfPrintMatrix(B);
3. mxDestroyArray(B);
. .
1 9
, mlfChar(). 1 6
mxArray *A = NULL;
mxArray *D1 = NULL;
mxArray *D2 = NULL;
3.2.5.
/* */ MATLAB
mlfAssign(&A, mlfChar(mxCreateString("my string"), . . 3.2.4
mxCreateString("my dog"),
NULL));
,
.
mlfPrintMatrix(A); . MATLAB C Math Library Reference.
194 3. 3.2. mxArray 195
3.2.4. mlfPrintMatrix(N);
MATLAB , [] ,
. , mlfIndexAssign().
, . , ,
, MAT , .
LAB . , MATLAB, A(2,2) = {17}.
mlfNum2cell(), : {?,?}.
mlfStruct2cell(). , .
, , mxArray *A = NULL;
mlfIndexAssign(&A,
, mlfNum2cell(). "{?,?}", /* () */
mxArray *N = NULL; mlfScalar(2), /* */
mxArray *C = NULL; mlfScalar(2), /* */
mlfScalar(17)); /* */
/* Create a numeric array */ mlfPrintMatrix(A);
mlfAssign(&N, mlfOnes(mlfScalar(2),mlfScalar(3),NULL)); mxDestroyArray(A);
196 3. 3.2. mxArray 197
, . mlfScalar(13), /* */
NULL));
[] []
mlfPrintMatrix(A);
[] [17]
mlfDestroyArray(A)
. :
mlfPrintMatrix() mlfDisp() ,
name: 'Polin'
, , number: 13
( mlfStruct()
). , , NULL.
mlfCelldisp(). mlfStruct()
, 11.
3.2.6. MATLAB , MATLAB,
MATLAB , , (1,1). MATLAB
. . , .
, , MATLAB
. . 3.2.5 , mlfCell2struct().
, ,
. . ,
. MATLAB C Math Library Reference. , mlfCell2struct().
mxArray *C = NULL; /* cell array to convert */
mxArray *F = NULL; /* cell array of field names */
3.2.5. MATLAB mxArray *S = NULL; /* structure */
/* */
mlfStruct() mlfAssign(&C, mlfCellhcat(mxCreateString("tree"),
mlfCell2struct() mlfScalar(37.4),
mlfFieldnames() mxCreateString("birch"),
mlfIsfield() NULL));
mlfGetfield()
/* */
mlfSetfield() mlfAssign(&F, mlfCellhcat(mxCreateString("category"),
mlfRmfield() mxCreateString("height"),
mxCreateString("name"),
NULL));
.
: /* */
; mlfAssign(&S,mlfCell2struct(C,F,mlfScalar(2)));
;
mlfPrintMatrix(C);
. mlfPrintMatrix(S);
. ,
mlfDestroyArray(C);
mlfStruct(). mlfDestroyArray(F);
. , mlfDestroyArray(S);
, : mlfCellhcat() ,
. NULL. :
mxArray *A = NULL; 'tree' [37.4000] 'birch'
, . mlfAssign(),
, mlfIndexAssign(). . ,
( ), , , .
, . mxDestroyArray().
. 3.4. 4. ,
MATLAB, A(2) = struct(name,jim,number,312). .
mxArray *A = NULL; MATLAB. ,
mlfIndexAssign(&A, mlfPrintMatrix().
"(?)", /* */
mlfScalar(2), /* */
MATLAB .
mlfStruct(mxCreateString("name"), /* */ 22 , ,
mxCreateString("Jim"), /* */ mlfPrintMatrix() .
mxCreateString("number"),/* */
mxArray *A = NULL;
mlfScalar(312), /* */
mlfAssign(&A,mlfOnes(mlfScalar(2),mlfScalar(2),NULL));
NULL));
mlfPrintMatrix(A);
mxDestroyArray(A);
mlfPrintMatrix(A);
mlfDestroyArray(A); :
, , 12 1 1
: 1 1
name , mlfPrintMatrix()
number , , (
mlfIndexAssign(), ).
, . 3.5. , mlfCelldisp().
.
3.2.7. , mlfFprintf().
. ,
%d, mlfFprintf()
, . mlfFprintf()
MATLAB: , . mlfFprintf()
MATLAB; ,
MATLAB; mlfFprintf() , mlfScalar(1).
, ; 5. mlfFprintf() mlfPrintf(). mlfFprintf()
mxArray C. MATLAB, mlfPrintf() .
mlfPrintf () , printf(), ,
MATLAB.
MATLAB.
MATLAB,
. 3.7.
.
22 A,
.
. ,
, , . mxArray *A = NULL;
mlfAssign(&A,mlfOnes(mlfScalar(2),mlfScalar(2),NULL));
, , mlfFprintf(mlfScalar(1), /* */
. mxCreateString("Array A = %d\n"), /* */
A, /* */
NULL);
.
, , , mlfFprintf()
mxArray, . .
200 3. 3.2. mxArray 201
array A = 1 ,
array A = 1
, .
array A = 1
array A = 1 .
. mlfNdims(). mlfNdims()
, . 232.
1, /* Determine dimensions */
mlfAssign(&ndims, mlfNdims( A ));
, 0 .
mlfFprintf(mlfScalar(1),
3.2.6. mxCreateString("The array has %d dimensions"),
ndims,
NULL);
mlfIsnumeric()
mlfIschar() mxDestroyArray(A);
mxDestroyArray(ndims);
mlfIssparse()
mlfIscell() 3, ,
mlfIscellstr() .
mlfIsstruct() mxAray .
. , mxArray . . 3.2.7
mlfSize(). , .
. 232 . 4.
dims :
mxArray *A = NULL; 3.2.7.
mxArray *dims = NULL;
/* 3- */ mxDuplicateArray
mlfAssign(&A, mlfOnes(mlfScalar(2), mlfScalar(3), mlfScalar(2), NULL)); mxGetCell
mxGetData
/* */ mxGetDimensions
mlfAssign(&dims, mlfSize(NULL,A,NULL)); mxGetElementSize ,
,
, mlfSize(2) mxGetEps eps
mxGetField
.
, mlfLength(). mxGetFieldByNumber
, .
mlfSize() mxGetFieldNameByNumber
.
mxGetFieldNumber
mlfVarargout().
, , mxGetImagData
. 3.5. mxArray
: dim1, dim2, mxGetInf
dim3. , . mxGetM, mxGetN (M) (N)
mlfSize(mlfVarargout(&dim1,&dim2,&dim3,NULL), C, NULL);
mxGetName, mxSetName mxArray
mxDestroyArray(dim1); mxGetNaN
mxDestroyArray(dim2); mxGetNumberOfDimensions
mxDestroyArray(dim3); mxGetNumberOfElements
202 3. 3.3. 203
3.2.7. (=)
() mxArray *. ,
mxArray * (
mxGetNumberOfFields mxArray NULL) .
mxGetPi, mxGetPr :
mxArray ,
mxGetScalar ;
mxArray , .
mxGetString mxArray
.
mxSetCell
mxSetData .
mxSetDimensions / : .
,
mxSetField
,
mxSetFieldByNumber mxArray *.
mxSetImagData
mxArray
mxSetIr i mxArray
mxSetJc j mxArray
mxSetLogical
mxSetM, mxSetN (M) (N)
mxSetNzmax
mxSetPi, mxSetPr mxArray
. 3.3.1.
3.3.
m MATLAB .
. mxArray.
, .
fun1(fun2(x)). ,
C. , .
.
. , .
. . ,
, , , mlfAssign()
, , . .
.
3.3.1. ,
.
.
: mxDestroyArray().
. .
. , MATLAB
mxArray , . C, .
204 3. 3.3. 205
MATLAB: 3.3.2.
z = sin(x) + cos(y)
C :
mxArray *temp_x, *temp_y; ,
, mlfEnterNewContext() mlfRestorePrevious
temp_x = mlfSin(x);
temp_y = mlfCos(y); Context().
z = mlfPlus(tempx, temp_y); :
mxDestroyArray(temp_x); 1. , :
mxDestroyArray(temp_y); ?
C : ?
mlfAssign(&z, mlfPlus(mlfSin(x), mlfCos(y))); ?
2. NULL
MATLAB. , , . , mlfAssign(), ,
. NULL
( .
). , 3. mlfEnterNewContext()
mxArray *
. (bound).
, mlfRestorePreviousContext() .
, , 4.
, mlfAssign(), (=).
. 5. ,
, , mxDestroyArray().
. .
. 6. mlfRestorePreviousContext()
, . , ,
1. , . ,
( mlfAssign()) mlfEnterNewContext().
. 7. mlfReturnValue()
: .
mlfSin(X); .
, mlfSin(), , , , , ,
. .
2. mxArray * mem_mgt_func_template.c <matlab>/
mxDestroyArray() . extern/examples/cmath/. ,
3. (=), (). ,
. (Unexpected program , . ,
termination) . x mlfEnterNewContext() mlfRestorePreviousContext()
. x , , FunctionName. mlfReturnValue()
x. x , FunctionName.
. mxArray *FunctionName(mxArray **output_arg1, mxArray *input_arg1,
x = mlfSin(y); /* x . */ mxArray *input_arg2)
a = mlfPlus(x, mlfScalar(1)); /* x . */ {
b = mlfPlus(a, x); /* . */ mxArray *local_return_value = NULL;
206 3. 3.3. 207
mxArray *local_var1 = NULL; (mxArray **) ,
mxArray *local_var2 = NULL;
mlfEnterNewContext(1,2, output_arg1, input_arg1,
. output_arg1;
input_arg2); (mxArray *) ,
. input_arg1 input_arg2.
/* . */
/* .... */ 1. , mxArray **
mxArray * . , char*
/* : local_return_value */ int,
mxDestroyArray(local_var1);
mxDestroyArray(local_var2); , mlfEnterNewContext().
mlfRestorePreviousContext(1,2,output_arg1, input_arg1, mlfEnterNewContext()
input_arg2); ,
return mlfReturnValue(local_return_value); .
} , .
mem_mgt_main_template.c main 2. mlfEnterNewContext() ,
<matlab>/extern/examples/cmath/. , ,
main() . , ,
. 0 mlfEnterNewContext() mlfRestorePrevious ,
Context() , main() mlfRestorePreviousContext(). ,
. mlfReturnValue() . NULL , .
mlfEnterNewContext(). ,
, mxArray * :
mlfEnterNewContext(). , mlfAssign()
. mlfEnterNewContext() mxArray *;
mlfAssign(). (NULL
mlfEnterNewContext() , ) .
.
mlfAssign(&dest, src).
mlfEnterNewContext()
src ( )
, . ,
*dest ( ). src
,
, mlfAssign() ,
,
. :
.
mlfEnterNewContext() mlfAssign(&Y, mlfCos(X));
. Y mlfCos() mxArray.
(NULL). mlfAssign() .
: ,
mlfEnterNewContext(int nout, int nin, mxArray **, mxArray *); mlfAssign().
: 3. mlfAssign(), ,
(int nout) . (=).
. 0,
( main()). mlfAssign() (=).
; 4. MATLAB ,
(int nin) , ,
. 0, ( mlfAssign() ( ),
main()). . ,
;
208 3. 3.3. 209
. 3.4.1.
, .
mlfReturnValue() return . ,
: .
mxArray *mlfReturnValue(mxArray *a);
:
return mlfReturnValue(local_return_value);
mlfReturnValue(), ,
(, main()
mlfReturnValue()).
8. ,
mlfReturnValue(), ,
mlfAssign(), mlfReturnValue(). . 3.4.1.
:
...
mlfAssign(&result_local, mlfSqrt(mlfPlus(mlfSin(x_in), mlfCos(x_in)))); ,
return mlfReturnValue(result_local); mxArray * . ,
...
mlfReturnValue()
mlfIndexRef(A, "(?,?)", mlfScalar(3), mlfScalar(1))
.
A.
return.
9. <matlab>/extern/examples/cmath/ex2.c. mlfIndexRef(A, "(?)", mlfScalar(9))
ex2.c, , A.
. 1. MATLAB
MATLAB C Math Library. : , .
N
,
3.4. . ,
MATLAB , .
. MATLAB, .
, .
. ,
, MATLAB, .
. , ,
: mlfCreateColonIndex().
mlfIndexRef() , .
; . mlfCreateColonIndex()
mlfIndexAssign() , , ( )
; ( ). mlfColon(),
mlfIndexDelete() , MATLAB .
. , mlfColon(mlfSclar(1), mlfScalar(10), NULL)
, [ 1 2 3 4 5 6 7 8 9 10 ].
. . MATLAB
MATLAB . .
212 3. 3.4. 213
, mlfIndexAssign(). .
. . mlfIndexAssign()
A , ,
. , A(3) . . :
, MATLAB mlfIndexAssign(&A, "(?,?)", mlfScalar(2), mlfScalar(1),
, mlfScalar(17));
. , A [d1 d2], d1 mlfIndexDelete(). .
d2 . .
(i,j) k , mlfIndexRef() mxArray *
k = (j-1)*d1+i. , mlfIndexAssign() mlfIndexDelete() mxArray **
, A(3,2) MATLAB ( , &A).
k = (21)*3+3 = 6. .
. " ".
. , (i,j,k,l) , "(?,?)" ,
[d1 d2 d3 d4]. MATLAB s . mxArray *
. ,
() .
s = (l-1)(d3)(d2)(d1)+(k-1)(d2)(d1)+(j-1)(d1)+i
, {} .
,
:
. ,
"(?,?,?,?)" ;
. ,
"{?}" ;
(3,2,1,1,1,1,1,1) (3,2).
"(?,?).date{?}" ; ,
.
3.4.2. 1. NULL
. .
mlfIndexRef(). . , .
. : . MATLAB
mlfIndexRef(A, "(?,?)", mlfScalar(2), mlfScalar(1)) B{3}(7).bfield(2,1) B,
, . , ,
mlfIndexAssign() mlfIndexDelete() , , bfield,
mxArray **, mlfIndexRef() (2,1).
, mxArray *. mlfIndexRef(B, "{?}(?).bfield(?,?)",
. mlfScalar(3), mlfScalar(7),
mlfScalar(2), mlfScalar(1));
MATLAB. (), {} .field (
) , , MATLAB ,
MATLAB, ?
. .
. mlfIndexRef(), mlfIndexRef()
, . , MATLAB
? . mxArray x(y(4)) = 3
*, mlfScalar(),
mxArray * mlfIndexAssign(&x, "(?)", mlfIndexRef(y, "(?)", mlfScalar(4)),
. mlfScalar(3));
214 3. 3.4. 215
MATLAB A, ,
D = A(foo(1,B(2,3)), bar(4,C(:))) mlfVertcat() :
2
5
mlfAssign(&D, 8
mlfIndexRef(A,"(?,?)",
foo(mlfScalar(1), , ,
mlfIndexRef(B,"(?,?)",mlfScalar(2),mlfScalar(3))), ,
bar(mlfScalar(4),
mlfIndexRef(C,"(?)",mlfCreateColonIndex()))));
. MATLAB end,
. , A(6:end)
A(6) . end()
. ,
mlfEnd().
, ,
mlfEnd():
. A, ,
mxArray *mlfEnd(mxArray *array, mxArray *dim, mxArray *numindices);
1 4 7
2 5 8 :
3 6 9 array ;
dim , ;
3.4.3. numindices ,
, .
, . (1 = , 2 = , 3 = . .)
. , mlfEnd() ( 11
, mlfIndexRef() ) .
, . mlfEnd()
, , .
mlfCreateColonIndex(). ( ) 1. C , ,
. A, A(6:end) MATLAB.
, mxArray *end_index=NULL, *B=NULL;
. mlfAssign(&end_index,
, mlfColon(mlfScalar(6),
mlfEnd(A, mlfScalar(1), mlfScalar(1)), NULL));
mlfAssign(&B, mlfIndexRef(A, "(?)", end_index));
mlfAssign(&B, mlfIndexRef(A, "(?)", mlfScalar(5)));
mlfScalar(1) mlfEnd() ,
B = A(5) MATLAB mlfEnd(), , .
A, 5. mlfScalar(1) ,
, , .
mlfIndexRef(A, "(?)", A: 6 7 8 9.
mlfHorzcat(mlfScalar(2), mlfScalar(5), mlfScalar(8), NULL))
A([2 5 8]) MATLAB , . , B
A: :
2 1 2
5 3 2
8 C , ,
13, mlfAssign(*C, mlfMagic(mlfScalar(3))),
13. 8 1 6
mlfAssign(&B, mlfIndexRef(A, "(?)", 3 5 7
mlfVertcat(mlfScalar(2), mlfScalar(5), mlfScalar(8), NULL))); 4 9 2
216 3. 3.4. 217
.
, , ;
, . , :
, , mlfAssign(&C,
. , 8 A mlfIndexRef(N, "(?,?)", mlfScalar(1), mlfScalar(2)));
: C 11,
mlfIndexDelete(&A, "(?)", mlfScalar(8)); 'smol'.
,
A 8:
, . ,
1 2 3 4 5 6 7 9
N, :
, mlfAssign(&B, mlfIndexRef(N, "(?,?)",
, mlfScalar(2),
. : mlfCreateColonIndex()));
mlfIndexDelete(&A, "(?,?)", mlfScalar(2), B 12 ,
mlfCreateColonIndex()); 13i 13.
: .
1 4 7 N,
3 6 9 v, 1 4 ( v
2. N mlfHorzcat()). mlfIndexRef() :
, . mlfAssign(&B, mlfIndexRef(N, "(?)", v));
. , B 12 , 22
2, 2 ( (1,1) N) 13 ( (2,2) N). MATLAB
. B = N([1 4]) .
,
3.4.4. , ,
, .
N , . mlfAssign(&,
MATLAB, mlfIndexRef(N, "{?,?}", mlfScalar(1), mlfScalar(2)));
. MATLAB . 'smol'. MATLAB = N{1,2}
, () .
. ,
{} , . . , (2,2)
. N{1,1}, "{?,?}(?,?)".
N, 22 double, , .
, , . 3.4.2. mlfAssign(&d,
mlfIndexRef(N, "{?,?}(?,?)",
mlfScalar(1), mlfScalar(1),
mlfScalar(2), mlfScalar(2)));
d 4. d = N{1,1}(2,2)
MATLAB. , d , .
.
, .
,
. 3.4.2. .
222 3. 3.4. 223
, A . A mlfIndexDelete(),
12 , 22 , , mlfIndexRef().
{1,2}. , ,
, :
mlfIndexDelete(&N, "(?,?)",
mlfScalar(2),mlfCreateColonIndex());
3.4.5.
MATLAB C, ,
.
, . ,
, .
summer : , .
. 3.4.3. MATLAB :
summer.image = image1;
. 22 , summer.description = ' ';
summer.date.year = 2005;
(1,2) : summer.date.month = 07;
mlfIndexRef(A, "{?,?}", mlfScalar(1), mlfScalar(2)) summer.date.day = 20;
MATLAB A{1,2} . summer : image, description date. date
. 13 , : year,
{2,2} {1,2} : month day. ,
mlfIndexRef(A, "{?,?}{?,?}", , (), (
mlfScalar(1), mlfScalar(2), ) ().
mlfScalar(2), mlfScalar(2))
A{1,2}{2,2} MATLAB . , .
. :
. .
mlfIndexAssign(). , [1 2 5 7 11] .
(1,2) A, : .
mlfIndexAssign(&A, "{?,?}", mlfScalar(1), mlfScalar(2), vector); , ,
vector . , .
MATLAB A(1,2) = {[1 2 5 7 11]}. , , .
:
mlfIndexAssign(&A, "(?,?)", mlfScalar(1), mlfScalar(2), ( ),
mlfCellhcat(vector,NULL)); : mlfIndexRef(), mlfIndexAssign(), mlfIndexDelete ().
.
, , , ,
( ) . mlfIndexRef(). ,
C . , :
. mlfAssign(&B, mlfIndexRef(summer, "(?)", mlfScalar(2)));
, ( ) 11.
. , image,
, . summer,
224 3. 3.5. 225
. varargin X , size
MATLAB, ,
, . MATLAB [d1,d2,d3,d4] = size(X)
, size :
. varargin mlfSize(mlfVarargout(&d1,&d2,&d3,&d4,NULL),X,NULL);
, ,
X, d1, d2, d3, d4 mxArray * . d1, d2, d3, d4
.
NULL. mlfSize()
, ... ( )
.
MATLAB, varargin
NULL.
. , MATLAB cat :
3. mlfSize() varargout.
B = cat(dim,A1,A2,A3,A4,...)
varargout
cat . dim A1 . , ,
cat . ,
dim. varargout mlfVarargout().
C , varargout. varargout
. MATLAB varargin mlfVarargoutList.
. mlfVarargoutList ,
(...). , , :
mlfCat() mxArray *mlfVarargout_function(mxArray **y,
mxArray *mlfCat(mxArray *dim, mxArray *A1, ...); mlfVarargoutList *varargout,
C mxArray *a,
mxArray *b);
, ,
MATLAB varargin mlfVarargoutList ,
. mlfCat() : . .
,
mlfAssign(&B, mlfCat(mlfScalar(2),A1,A2,A3,A4,A5,A6,NULL));
mlfVarargoutList. mlfVarargout() mlfIndexVarargout().
B mxArray * , NULL.
varargout varargout ,
A mxArray * .
, :
2. varargin mlfVarargout(),
NULL. varargout ;
. MATLAB
mlfIndexVarargout(),
. MATLAB
varargout .
varargout . varargout
MATLAB, varargout.
, . , varargout ,
varargout MATLAB, MATLAB mlfVarargoutList, mxArray* mlfVarargout().
, varargout. :
. MATLAB mlfVarargoutList *mlfVarargout(mxArray **pp_array, ...);
. , mlfVarargout() mxArray**,
... NULL. ,
MATLAB, varargout. , MATLAB size, varargout , varargout mlfVarargout_
Function, , mlfVarargout()
.
[M1,M2,M3,...,MN] = size(X); mlfAssign(&x, mlfVarargout_Function(&y,
230 3. 3.5. 231
/* MFuncTab[]*/ yp = mxGetPr(ypm)
static mlfFuncTabEnt MFuncTab[] = /* 1 */
mxArray ypm.
{
{"lorenz", (mlfFuncp)lorenz, _lorenz_thunk_fcn_ }, lorenz.
{0, 0, 0} thunk,
};
lorenz. thunk ,
mxArray *lorenz(mxArray *tm, mxArray *ym) /* 2 */ , ,
{ MATLAB.
mxArray *ypm = NULL;
static int _lorenz_thunk_fcn_(mlfFuncp pFunc, int nlhs, /* 1 */
double *y, *yp;
mxArray **lhs, int nrhs,
mlfEnterNewContext(0, 2, tm, ym);
mxArray **rhs )
{
/* 31 ypm lorenz */
typedef mxArray *(*PFCN_1_2)( mxArray * , mxArray *); /* 2 */
/* - y yp */
mxArray *Out;
mlfAssign(&ypm, mlfDoubleMatrix(3, 1, NULL, NULL));
y = mxGetPr(ym);
if (nlhs > 1 || nrhs > 2) /* 3 */
yp = mxGetPr(ypm);
{
return(0);
yp[0] = -BETA*y[0] + y[1]*y[2]; /* 3 */
}
yp[1] = -SIGMA*y[1] + SIGMA*y[2];
yp[2] = -y[0]*y[1] + RHO*y[1] - y[2];
Out = (*((PFCN_1_2)pFunc))( /* 4 */
(nrhs > 0 ? rhs[0] : NULL),
mlfRestorePreviousContext(0, 2, tm, ym);
(nrhs > 1 ? rhs[1] : NULL)
return mlfReturnValue(ypm);
);
}
: if (nlhs > 0) /* 5 */
1. MFuncTab[] lhs[0] = Out;
mlfFuncTabEnt. , return(1); /* 6 */
, mlfOde23(). }
: :
, ("lorenz"); 1. thunk, lorenz.
((mlfFuncp) lorenz); thunk
thunk, lorenz, , .
(_lorenz_thunk_fcn_). Thunk ,
{0, 0, 0}. (
mlfOde23() MFuncTab lorenz()):
mlfFevalTableSetup(), mlfFuncp , lorenz();
, . (nlhs) ,
, . lorenz();
2. , F(t, y) = lorenz(t, y). mxArrays (lhs) lorenz();
11 tm, t 31 ym, (nrhs) ,
y. 31 ypm, lorenz();
t. mxArrays (rhs) .
3. . : lhs (lefthand side, )
(lorenz tm, mlfOde23.) , MATLAB,
y = mxGetPr(ym) rhs (righthand side, ) ,
ym. yp. .
236 3. 3.5. 237
. , A B mxArray,
thunk, , thunk . C ,
, . mlfIndexRef() {1:5}
. , mlfFeval() C.
thunk. thunk mlfVarargin_Func().
. .
4. mxArray . .
. , . ,
varargin.
. . n mlfVarargin_Func(mlfIndexRef(C, "{?}", mlfColon(mlfScalar(1),
, 1 0 n1 mlfScalar(5), NULL)), A, B, NULL);
, 2 n 2n1 . . mlfVarargin_Func()
5. . , .
tm, mlfOde23. .
mxGetM mxArray.
ex4.exe : 3.6.
mbuild ex4.c
, MAT
. MAT. MAT ,
, : , MATLAB ,
t y1 y2 y3 . MAT
9.390 41.218 12.984 2.951
9.405 39.828 11.318 0.498
. MATLAB
9.418 38.530 9.995 -0.946 .
9.430 37.135 8.678 -2.043 mlfSave() mlfLoad()
9.442 35.717 7.404 -2.836 MATLAB load save. ,
9.455 34.229 6.117 -3.409
MATLAB
, MATLAB /C++.
3.5.3. , mlfSave() mlfLoad()
MATLAB MATLAB, MATLAB load save.
, . MAT. mlfSave(),
MATLAB mxArray . mlfSave()
. , MATLAB T{1:5} , void mlfSave(mxArray *file, const char* mode, ... );
T. file mxArray, MAT, mode
T . , ,
. ,
. , mxArray
, MATLAB varargin, . mlfSave() NULL,
mlfIndexRef(). , varargin . :
void mlfVarargin_Func(mxArray *A, mxArray *B, ...);
#include "matlab.h"
: mxArray *fname, *x, *y, *z;
mlfVarargin_Func(A, B, mlfSave(mxCreateString("fname"),
mlfIndexRef(C, "{?}", "w","X",x,NULL); /* "w" - */
mlfColon(mlfScalar(1), mlfScalar(5), NULL)), mlfSave(mxCreateString("fname"),
NULL); "u","X",x,"Y",y,"Z",z,NULL); /* "u" - */
240 3. 3.7. 241
: 1. ex5.c ,
mxArray, mlfSave() mlfLoad()
. 32 . . <matlab>\extern\
X, Y, Z. examples\cmath.
; .
ASCII ,
mlfSave(); mlfFprintf() mlfFscanf.
, mlfFopen,
; mlfFclose:
MAT .mat. mxArray *fid = NULL; /* */
.mat , mxArray *A = NULL; /* */
; mxArray *mode = 'wt'
, mlfAssign(&fid, mlfFopen(NULL,NULL,filename, "wt",NULL));
mlfAssign(&A, mlfFscanf(NULL,fid,format,size));
. : "w" , "u" ( mclAssignAns(&ans, mlfFclose(mclVv(fid, "fid")));
), "w4" W4;
MAT, ASCII.
MAT. mlfLoad(), mxAr
3.7.
ray MAT. mlfLoad() MATLAB C 400 .
void mlfLoad(mxArray *file, ... ); : MATLAB (BuiltIn
Library), m (MFile libraries)
file mxArray, MAT,
, .
, mxArray , , ,
. mlfLoad() NULL, , , , ,
. : .
#include "matlab.h" m , ,
mxArray *fname; /* */
mxArray *x, *y, *z; /* */ .
mlfLoad(fname,"X",&x,NULL));
mlfLoad(fname,"X",&x, /* / */ MATLAB
"Y",&y, MATLAB C++.
"Z",&z, mlf ,
...,
NULL)); /* NULL */ sin ++,
: mlfSin.
mxArray , ,
, "X", "Y", "Z"; C++ ( 1). ,
mlfLoad(); C Math Library
, MAT Reference MATLAB 6.
; ,
. ,
mlfLoad() . MATLAB.
; , MATLAB mlfSetPrintHandler().
, . :
.mat , mlfComputer ;
; mlfEps ;
MAT, ASCII. mlfI, mlfJ , 0+1.0i;
242 3. 3.7. 243
mlfInf ; . , MATLAB
mlfNan ; (:). , mlfColon(NULL, NULL,
mlfPi pi = 3.1415926535897...; NULL) mlfCreateColonIndex():
mlfRealmax ; mxArray *mlfColon(mxArray *start, mxArray *step, mxArray *end);
mlfRealmin . (:), mlfAr
MATLAB: rayRef(), mlfArrayAssign() mlfArrayDelete():
mlfLdivide (.\); mxArray *mlfCreateColonIndex(void);
mlfMinus (-); .
mlfMldivide (\); end MATLAB A(3,6:end), dim ,
mlfMpower (^); end, numindices .
mlfMrdivide (/); mxArray *mlfEnd(mxArray *array, mxArray *dim,mxArray *numindices);
mlfMtimes (*); .
mlfPlus (+); . .
mlfPower (.^); void mlfSetLibraryAllocFcns (calloc_proc calloc_fcn,
mlfRdivide (./); free_proc free_fcn,
mlfTimes (.*); realloc_proc realloc_fcn,
mlfUnaryminus,mlfUminus . malloc_proc malloc_fcn);
: . , printf.
mlfAll True, ; :
mlfAnd AND (&); int mlfPrintf(const char *fmt, ...);
mlfAny True, ; :
mlfNot NOT (~); void mlfPrintMatrix(mxArray *m);
mlfOr OR (|); :
mlfIsieee True IEEE ; void mlfSetPrintHandler(void (* PH)(const char *));
mlfIsspace True ; . 11 ,
mlfXor or. v:
mxArray *mlfScalar (double v);
11 ,
Math MATLAB C ,
v i:
, .
mxArray *mlfComplexScalar(double v, double i);
.
:
void mlfSetErrorHandler(void (* EH)(const char *, bool));
mlfFeval(). thunk
MATLAB C.
void mlfFevalTableSetup(mlfFuncTab *mlfUfuncTable);
. , :
mxArray *mlfIndexAssign(mxArray * volatile *pa, const char *index, ...);
, :
mxArray *mlfIndexDelete(mxArray * volatile *pa, const char *index, ...);
, :
mxArray *mlfIndexRef(mxArray *pa,const char* index_string, ...);
4.1. 245
. MATLAB 7(R14)
,
MATLAB Compiler_40.
, ++
4. ++
MATLAB C++ (dll)
.
MATLAB C++ . ,
MATLAB C++ 1.
++.
MATLAB C++ ( C++: ,
++, ++CML) 400 . ,
MATLAB. C++ MATLAB C++,
MATLAB C. , C++
, MATLAB. .
MATLAB C++ C++
m MATLAB. .
C++ mwArray.
C++. MATLAB MATLAB. mwArray
, MATLAB .
MATLAB C++ , , \, ./, .\, .* .^, ++.
.
.
m MATLAB
++, m,
. C++ 4.1.1.
MATLAB, . MATLAB C++
, , UNIX Windows Microsoft.
C++, . C++
MATLAB. C++ MATLAB, .
, . , MATLAB 6.5
, . , ,
7 Windows Compiler.
Borland C++ Builder
MATLAB C++
MATLAB C++.
C. ,
MATLAB ( <matlab>\extern\examples\cppmath)
C
.
.
C++ <matlab>\bin
$PATH. BIN DLL,
4.1. .
++ MATLAB, C++,
MATLAB 6.0. C/C++ .
MATLAB 6.5 Compiler, C/C++:
246 4. 4.1. 247
4.1.2.
4.1.2.
<matlab>\extern,
libmatpb50.lib MATLAB C++
, MATLAB, <matlab>\bin, libmatpb52.lib Borland C++, v5.0, v5.2 v5.3
<matlab> MATLAB. libmatpb53.lib
Microsoft Windows. libmatpm.lib MATLAB C++
<matlab>\bin. Microsoft Visual C++
(DLL), C, bat mbuild, libmatpw106.lib MATLAB C++
. <matlab>\bin libmatpw11.lib Watcom C++ , v10.6 v11
. DLLs
WIN32. , . 4.1.1. <matlab>\extern\include.
C++.
4.1.1. bin MATLAB C++ MATLAB C,
matlab.h matrix.h C++.
. 4.1.3 def Borland Microsoft
libmat.dll MAT) mlfLoad()
Visual C++. lib*.def MSVC++, _lib*.def
mlfSave()
libmatlb.dll MATLAB. Borland.
MATLAB. 4.1.3. include
libmi.dll MAT)
libmmfile.dll M) MATLAB. libmatlb.h ,
M) MATLAB. MATLAB
, libmmfile.h ,
m) MATLAB M) MATLAB
libmx.dll MATLAB. matlab.h C
matrix.h , mxArray
libut.dll MATLAB. ,
_libmat.def , MAT) DLL
mbuild.bat libmat.def
_libmatlb.def ,
compopts.bat , libmatlb.def MATLAB DLL
mbuild.bat. mbuild setup _libmmfile.def ,
C++ libmmfile.def DLL m) MATLAB
mbuild.bat , , msvccompp.bat _libmx.def , libmx.dll
Microsoft Visual C/C++ libmx.def
248 4. 4.1. 249
1. . Glava_7
C++ matlab.hpp Windows Borland C++ Builder,
. ++ MATLAB.
2. C++
C++. , 4.1.7.
C++ ,
C++ . C++,
3. average() ( MATLAB) C++.
const. , C++,
. average() mwArray mwAr MATLAB mbuild. ,
ray. , . C++ .
rdivide() plus() .
. , ,
5. mat0 mat1 2 2, .
, . MathWorks mbuild,
mat0 mat1 . mat0 2, 4, . mbuild :
6, 8. mat1 1, 3, 5, 7. ;
6. average(). mat0 mat1 .
mat2. C mbuild (
7. . ), mbuild .
C++:
. , (compopts.bat).
. . C/++
. mbuild
, DOS: :
mbuild ex4.cpp ;
ex4.exe. . ;
ex4.exe : <matlab>\bin.
[ mbuild .
2 4 ; , mbuild C++
6 8 . ,
]
.
+ Windows ,
[ MATLAB,
1 3 ;
. : Application
5 7
] Data\MathWorks\MATLAB\R12. mbuild
compopts.bat, setup
/ 2 = .
[
1.50000 3.50000 ; mbuild , C C++,
5.50000 7.50000 : .c C .cpp, .cxx, .cc C++. C C++,
] mbuild C++ C++.
1. Windows mbuild , C
. . C++, mbuild C.
256 4. 4.2. mwArray 257
. C++ 4.2.1.
MATLAB: ()
C++ MATLAB
: mwArray(const mwArray&) mwArray
, (
. MATLAB API)
; mwArray(int, int, int) 1))n
,
mwArray(const mwSubArray&) mwArray
; horzcat() m))n
; vertcat()
; cat()
, , (m))n))p)))
. ones()
zeros() (m))n))p))) ,
MATLAB C++ mwArray rand(), randn()
MATLAB. eye()
, () , magic()
, . ,
C++, . , mwArray ++
, . :
mwArray;
;
4.2.1. ;
C++ ;
. 4.2.1. .
. MATLAB C++ Math Library Reference. , , C++
MATLAB.
4.2.1. ++.
mwArray, , ,
mwArray A; . mwArray A;
,
empty() ([]) . ,
mwArray(double) mwArray. C++,
. , mwArray
(1))1)
, .
mwArray(int)
cat().
(1))1) 1. mwArray
mwArray(int, int, double*, 23, C++
double*) . C++
mwArray(int, int, int*, int*) m))n () , (unsigned short) , mwArray.
mwArray(int, int, unsigned (unsigned C++
short*, unsigned short*) short data) .
mwArray( mxArray *) mwArray mwArray 23.
260 4. 4.2. mwArray 261
: .
C =[ row2mat(), C++
(:,:,1) = . , :
[ static double data[] = { 1, 2, 3, 4, 5, 6 };
1 2 3; mwArray A = row2mat(2, 3, data);
4 5 6
] row2mat ,
(:,:,2) = . C++
[ , mwArray.
11 12 13;
14 15 16 colon() .
] ,
] .
, dim, , mwArray A;
, , cat A(colon(),colon(),2) = 4;
1 .
. , 4.2.2.
(=) ++. , C++ MATLAB C++
A 5. .
mwArray = 5;
11 ( , ), .
5.0, .
.
, .
, . .
( ),
. , 4.2.2.
C++
mwArray H;
H(2,2,2) = 5;
sparse()
, , H(2,2,2) full()
= 5. spones()
3. sprand()
. mwArray H(2,2,2) = 5 . sprandn()
. sprandnsym()
spconvert()
C++. mwArray,
speye()
. spdiags()
C++.
mwArray C++, nnz()
C++ . , any() all() ,
23, 1 2 3 4 5 6 ,
264 4. 4.2. mwArray 265
4.2.2. // mwArray
mwArray S;
()
mwArray i(1,6,inums,NULL);
mwArray j(1,6,jnums,NULL);
nzmax() ,
//
S = sparse(i, j, 9, 8, 7);
nonzeros() ,
cout << S << endl;
spfun()
cout << full(S) << endl;
:
. (4,3) 2
C++ sparse() . (5,3) 2
(3,4) 2
: (6,4) 2
; (4,5) 2
. (5,5) 2
[
sparse() 0 0 0 0 0 0;
. 0 0 0 0 0 0;
, . 0 0 0 9 0 0;
0 0 9 0 9 0;
mwArray A,B; 0 0 9 0 9 0;
A = eye(8); 0 0 0 9 0 0;
cout << A << endl; 0 0 0 0 0 0;
B = sparse(A); ]
cout << B << endl;
full()
64 8
.
.
,
nnz(). 44
. sparse()
, .
:
mwArray A = eye(5);
, i j, , cout << nnz(A) << endl;
;
, s,
. i, j s
4.2.3.
; MATLAB C++
, m n, .
; .
, . .
.
. , ,
.
76 . 2
. 4.2.3
.
// C++
double inums[] = {3,4,5,4,5,6}; .
double jnums[] = {4,3,3,5,5,4}; .
266 4. 4.2. mwArray 267
4.2.3. MATLAB,
.
mwArray("abcd")
, ,
char_func() , .
double_func() char_func(),
.
str2mat() , mwArray Z("my string");
strcat() , mwArray Y("my dog");
strvcat()
cellstr() mwArray Q = char_func(Z,Y);
cout << Q << endl;
char_func()
deblank() .
[
disp() 'my string';
num2Str() 'my dog ';
]
int2str() , char_func() "my
dog", "my string",
str2num() 29.
mwArray C; ;
C = cell(2,3,2);
cout << C << endl;
.
: MATLAB C++ cellhcat()
(:,:,1) = ({}) .
[] [] [] , 22,
[] [] [] , .
(:,:,2) =
[] [] []
,
[] [] [] .
, MATLAB mwArray D;
D(2,2) = cellhcat("kemer");
. ,
cout << D << endl;
, num2cell(),
, struct2cell(). :
, ones(), [] []
[] 'kemer'
, num2cell().
mwArray B = ones(3,4);
MATLAB C++ mwArray::
mwArray C = num2cell(B); cell()
MATLAB , , . ,
MATLAB ({}). ,
MATLAB C++ cellhcat() .
MATLAB {}. , .
14. Z{2,2} = 'kemer' MATLAB.
mwArray C; mwArray Z;
C = cellhcat( "kemerovo", ones(3), magic(4), 10 ); Z.cell(2,2) = "kemer";
cout << "C = \n" << C << endl; cout << Z << endl;
: , .
C = 4. mwArray::cell()
'kemerovo' [3x3 double] [4x4 double] [10] cell(). cell() .
, .
cellhcat() vertcat() (<<) .
: ,
mwArray C; . ,
C = vertcat(cellhcat("kemerovo",ones(3)),cellhcat(magic(4), 10 )); , MATLAB,
cout << "C = \n" << C << endl;
, .
: ,
C = celldisp(). :
'kemerovo' [3x3 double]
[4x4 double] [ 10]
, MATLAB,
.
, ,
, celldisp ().
, cat().
mwArray C = vertcat(cellhcat("kemer",10),
,
cellhcat(magic(4), ones(2,3,3)));
C++ ( ), cout << "cout output:\n" << C << endl;
. cout << "celldisp() output:\n" << endl;
: celldisp(C,"C");
270 4. 4.2. mwArray 271
mwArray C,F,S;
4.2.5. //
C = cellhcat("tree", 37.4, "birch");
,
//
. . F = cellhcat("category", "height", "name");
, //
. S = cell2struct(C,F,2);
MATLAB C++ , ,
. , MATLAB C++
struct_func() ; , , ,
cell2struct() ; .
fieldnames() ; , name number.
isfield() , ; ,
getfield() ; , .
setfield() ; ,
rmfield() . .
MATLAB C++ mwArray A;
A(4) = struct_func("name", //
:
"Polin", //
; "number", //
; 3); //
.
struct_func(). 4.2.6.
.
, ,
: . MATLAB
mwArray A;
mwArray ++ . ,
A = struct_func("name", // mwArray
"Polin", // .
"number", // mwArray.
3); //
cout << A << endl; C++ mwArray.
: mwArray.
name: 'Polin' ,
number: 3 mwArray. mwArray:
, struct_func() ;
. , ;
MATLAB . ;
, MATLAB mxArray;
MATLAB cell2struct(). mwSubArray.
, ,
. mwArray. MEX
C, , , F, C, , ,
. S mxArray mwArray,
cell2Struct(): MATLAB C++ mxArray.
272 4. 4.2. mwArray 273
A 1111 11 ,
. ExtractScalar() 11.
, , cdata ( ,
) , .
mwArray A = magic(11) + (rand(11) * i()); . 4.2.6 ,
double rdata, cdata; ,
rdata = A.ExtractScalar(9); // 9- .
rdata = A.ExtractScalar(cdata, 17); //
// 17- , cdata
4.2.6.
int32 *integers = new int32[ 11 * 11 ]; // 121
A.ExtractData(integers); // MATLAB ++ ++
double *real_data = new double [ 11 * 11 ]; // 121
double *complex_data = new double [ 11 * 11 ]; C = mwArray A, B, C; double C;
// real_data A(3)*B(4); C = A(3)*B(4); mwArray A, B; double
A.ExtractData(real_data); C = A(3)*B(4);
// n = mwArray n, A; int n;
A.ExtractData(real_data, complex_data); max(size(A)) n = max(size(A)); mwArray A; integer .
A(n) = n*n; A(n) = n*n; n = max(size(A)); ,
ExtractScalar() MN 1(M*N). A(n) = n*n;
, A.ExtractScalar(9) 9 .
ExtractScalar() , , mwArray
N (N+1). . ,
ToString(). mwArray, mwArray
mwArray ToString(). : .
mwArray A = "MATLAB";
mwString s = A.ToString(); mwArray . for
char *c = strdup((char *)s);
i<A mwArray .
mwString .
, , mwArray A = 5;
mwString . mwString int i;
, char *. for (i=0; i<A; i++)
cout << "Counting: " << i << endl;
ToString() char*
, strcat(str, A.ToString()). ,
mwString, strdup(), A , j
. , A for.
. mwArray A = 5;
int i, j = A;
7. mwString char* . for (i=0; i < j; i++)
, mwString . cout << "Counting: " << i << endl;
. .
. .
++ , :
, . size(),
, , , ;
mwArray. size(),
. , , ;
276 4. 4.2. mwArray 277
, , 1 1 4
2 3 2
colon().
3 6 9
.
, empty().
. C++
, . , .
B:
,
1 0 1
0 1 0 ,
1 0 1 , , .
logical(), , (8) A
mwArray B = logical(vertcat(horzcat(1,0,1), A(8) = empty();
horzcat(0,1,0), : 1 2 3 4 5 6 7 9.
horzcat(1,0,1)));
,
A(B) : . :
1 A(2,colon()) = empty(); //
3
5 :
7 1 4 7
9 3 6 9
, , ,
, . , B = , empty().
[1 0; 0 1], A(B) 1. N > 2, N
1 , .
4 , , .
B 2 3 1 4. , ,
, . .
colon()
. 4.3.2.
. , , colon()
, , , ,
. , B = [1 0 1]. , ,
A(colon(),B) : , ,
1 7 .
2 8 N 22, :
3 9 22, , ,
. , , .
MATLAB.
mwArray , MATLAB.
.
. , B
1 2 C 2 3.
A(B,C) = vertcat(horzcat(1, 4) horzcat(3, 2));
22 ,
A. A : . 4.3.1. N
284 4. 4.3. 285
MATLAB : d = N.cell(1,1)(2,2);
N{1,1} = [1 3; 2 4]; N{1,2} = 'smol'; , d , , d = 4.
N{2,1} = 1-3i; N{2,2} = 13; .
++: , . , A, .
N.cell(1,1) = vertcat(horzcat(1, 3), horzcat(2, 4)); 4.3.2, : 12
N.cell(1,2) = "smol"; 22, (1,2).
N.cell(2,1) = complex(1,-3);
N.cell(2,2) = 13;
MATLAB, C++
.
() .
mwArray::cell() , .
cell().
, N N.cell(2,2)
C++ 13, N(2,2) ,
13.
, . 4.3.2.
. colon()
, . 22,
, (1,2):
. A.cell(1,2)
, . 11,
( ) , (2,2) (1,2):
, , A.cell(1,2).cell(2,2)
C = N(1,2);
. ,
11, 'smol'. ,
. . ,
N v , [1 2 5 7 11] (1,2) N, N{1,2} = [1
1 4, 2 5 7 11] MATLAB
B = N(horzcat(1, 4)); N.cell(1,2) = horzcat(1, 2, 5, 7, 11);
B 12, C++.
22 ( (1,1) N) 13 ( (2,2) N). MATLAB N(1,2) = {[1 2 5 7 11]}. C++
. :
, mwArray cell() N(1,2) = cellhcat(horzcat(1, 2, 5, 7, 11));
, . cell().
C = N.cell(1,2); , , ,
C 'smol'. ( ) .
. ,
. .
, (2,2) N(1,1), , .
, ,
( mwArray cell()), , . , (2,1) N ( 13i)
( ): . (2,1) N :
286 4. 4.3. 287
N(2) = empty(); .
,
. .
, . ,
N(2,colon()) = empty(); .
2. N.cell(2,colon()) = empty() , , , .
.
. N [],
N.cell(2,colon()) = cellhcat(empty(),empty()), . image
12 12. :
image = summer(2).field("image");
4.3.3. MATLAB .
, ,
C++
. , , . mwArray::field()
() . . ,
, mwArray::field(), :
, field(). n = summer(3).field("image")(1,colon());
MATLAB ,
, . . , , . ,
. summer , :
: (image), (description) summer(17).field("description") = "";
(date). MATLAB MATLAB summer(17).description = ''
: .
summer.image = image1; ,
summer.description = ' ';
summer.date.year = 2005; . ,
summer.date.month = 07;
summer.date.day = 20; :
date B = summer(42);
: year, month day. , MATLAB B = summer(42) .
. summer ()
. ,
(), () ().
, , date.
11,
, mwArray::field().
5 11.
y = summer(2).field("date").field("year");
,
. , MATLAB y = summer(2).date.year .
MATLAB 342 , .
342 : , ,
summer(3,4,2).image = image24; , ;
summer(3,4,2).description = ' '; . ,
summer(3,4,2).date.year = 2005;
summer(3,4,2).date.month = 07;
.
summer(3,4,2).date.day = 24; ,
, , :
. second_date = c.cell(1)(2).field("date");
288 4. 4.4. 289
MATLAB , .
. mwVarargin 32 ,
mwVarargin,
. , svd() . .
.
. mwVarargin 31 mwArray.
. , mwVarargin varargin:
. mwVarargin, 31 mwArray
S = svd(X);
. mwVarargin ,
U = svd(&S, &V, X); .
U = svd(&S, &V, X, Zero); , mwVarargin,
U, S, V, X Zero mwArray. U, S , 31 .
V mwArray. , mwVarargin.
(&) , horzcat(),
. & , , varargin. 90 horzcat
MATLAB. C++ &, :
, . horzcat(mwVarargin(mwVarargin(p1,p2,...,p32), p33, ..., p63),
p64, ..., p90);
:
mwArray , 32 mwVarargin,
mwArray * mwVarargin. 31
. ( p33 p63) mwArray mwVarargin,
, . horzcat(). ( p64
MATLAB, , p90) mwArray.
MATLAB , 1. ,
mwVarargout
.
, mwVarargin
.
.
MATLAB ,
. MATLAB
varargin. varargin
. MATLAB varargout
MATLAB,
. varargout
,
MATLAB,
. MATLAB , .
, . varargout MATLAB, MATLAB
(varargin) , varargout.
, . .
C++ , C++
, C++ mwVarargout, . :
varargin mwVarargin. , size(mwVarargout(d1, d2, d3, d4), X);
C++ cat,
X d1, d2, d3 d4 mwArray. ,
, , MATLAB, 32
mwArray mwVarargout ,
. :
.
B = cat(2,A1,A2,A3,A4,A5,A6);
varargout ,
B A mwArray. mwVarargout. mwVarargout,
, 32 , varargin mwVarargout
C++, mwVarargin, . mwVarargout
292 4. 4.4. 293
4.4.3. 3. .
,
(ex3.cpp) mwArray mwArray *, const mwArray&.
C++, FEVAL.
. #include <stdlib.h>
<matlab>\extern\examples\cppmath. #include "matlab.hpp" //
MATLAB C++,
fmins() fzero(), , // , sqrt(x)* log(x)
mwArray func1(mwArray x) // # 1
. fmins() " {
", , ( return(times(realsqrt(x), reallog(x)));
3.5.2). }
// feval func1() -
DECLARE_FEVAL_TABLE // # 2
. FEVAL_ENTRY(func1)
C++: , , END_FEVAL_TABLE
feval; thunk,
int main(void)
, .
{
, try {
. . , cout << fmins("func1", 0.25) << endl; // # 3
, , }
catch (mwException &ex)
, , 8, ,
{
5, . cout << ex;
thunk feval. }
3.5.2, . return(EXIT_SUCCESS);
}
MATLAB.
, ,
C++ mlfFeval() C. :
mlfFeval() thunk, 1. func1(). fmins().
. thunk C, fmins()
. . 3.5.2 " MATLAB C, func1().
" , func1()
mlfFeval() thunk. . , reallog() realsqrt(),
2. thunk ,
. .
feval C++ 2. feval func1(),
. , MATLAB feval().
++, , DECLARE_FEVAL_TABLE
feval. END_FEVAL_TABLE. func1
, FEVAL_ENTRY. .
feval(), feval. :
, 0 8 DECLARE_FEVAL_TABLE
FEVAL_ENTRY(function_name1)
1 5 . feval thunk, FEVAL_ENTRY(function_name2)
typedef, mlfFuncTabEnt, feval_init, ( ...)
. END_FEVAL_TABLE
296 4. 4.4. 297
C, sqrt(), . C
IEEE:
4.5.
NaN. sqrt() , C++
MATLAB C++ , .
i, 1.
C++ 4.5.1. ,
,
C++ . C++
, mwArray.
(, , . .). C++
MATLAB, sqrt() abs(),
, cin, cout, cerr. cin
.
, cout , cerr
. ,
. MATLAB C++ ,
C++, (>>) (<<) mwArray.
mwArray .
, A , :
sqrt():
cout << A << endl;
mwArray a = -5;
sqrt(a); A :
mwArray : cin >> A;
sqrt((mwArray)-5); sqrt(mwArray(-5)); A , :
. cerr << A << endl;
mwArray , C++
. , .
MATLAB C++ char double C++. ,
clock() ++ . , <<,
. , MATLAB , ,
C++, , >>. /
MATLAB C++ _func. MATLAB ex1.cpp C++,
. 4.4.3 , . <matlab>/extern/examples/cppmath.
. DOS,
4.4.3. MATLAB C++ Math Library ([), .
MATLAB C++ , .
(]).
and and_func
bitand bitand_func
. ,
bitor bitor_func . . ,
char char_func : [1 2; 3 4]. :
clock clock_func [
double double_func 1 2;
not not_func 3 4
]
or or_func
pascal pascal_func (PC only) ,
quad quad_func
std std_func . ([ ]),
struct struct_func .
union union_func /.
xor xor_func MATLAB C++
300 4. 4.5. 301
, , C++
, . .
mwArray(const char *str). .
mwArray. C++ .
mwArray (int32 rows, int32 cols, double *real, double *imag = 0).
. mwArray ,
mwArray. .
MATLAB mwArray. . .
.
4.6.1. , , imag,
. imag .
mwArray . .
mwArray : , , mwArray(const mwArray &mtrx). mwArray.
, mxArray * mwArray. C++, .
. , .
, .
4.6.1. mwArray
mwArray(const mxArray *mtrx). mwArray mxArray* .
C
mwArray() mwArray A; API. .
mwArray(const char *) mwArray A("MATLAB mwArray(double start, double step, double stop).
Rules"); . ,
mwArray(int32, int32, double real[] = { 1, MATLAB . , mwArray (1, 0.5, 3)
double*, double*) 2, 3, 4 };
[1, 1.5, 2, 2.5, 3].
double imag[] = { 5,
6, 7, 8 }; mwArray(int32 start, int32 step, int32 stop).
mwArray .
A(2,2,real,imag); mwArray(const mwSubArray & a). mwArray mwSubArray.
mwArray(const mwArray A = rand(4); ,
mwArray&) mwArray B(A); , mwSubArray. mwSubArray
mwArray(const , mxArray* mxArray *m = . ,
mxArray *) mlfScalar(1); .
mxArray* mwArray mat(m);
, mwSubArray,
mwArray(double, mwArray A(1.2, 0.1,
double,double) 3.5); .
(Ramp) mwArray(double). mwArray 11
mwArray(int32, int32, mwArray A(1, 2, 9); .
int32) (Integer ramp) mwArray(int). mwArray .
mwArray(const ) mwArray A = rand(4);
, mwArray B(A(3,3));
mwSubArray&)
mwArray(double) mwArray A(17.5);
4.6.2.
mwArray(int) mwArray A(51); mwArray ,
:
. operator() "" ,
mwArray(). . , ;
, cell() ;
C++. , field() .
310 4. 4.6. mwArray 311
5.1. MATLAB
, MATLAB.
MATLAB (mcc) m C
C++ P. MATLAB
C C ++ :
MEX;
;
C ( )
C++ ;
S Simulink;
Excel;
COM (Component Object Model).
3.0 MATLAB MATLAB
C/C++ MATLAB C/C++. MATLAB
C/C++.
,
MATLAB C/C++ . ,
,
. MATLAB
6.5 (R13) ,
,
. MATLAB 7.0 (R14)
MATLAB C/C++ .
316 5. MATLAB 3.0 5.1. MATLAB 317
. MEX MEX,
MEX. MEX MEX. MEX
yprime.c, <matlab>\extern\examples\mex. .
MATLAB mexFunction. MATLAB
: . MEX
mex yprime.c MATLAB , MATLAB. MATLAB
MEX yprime.dll. yprime MEX, m. MEX
MATLAB: , m.
yprime(1,1:4)
MEX . [8].
ans = MATLAB mcc, -x,
2.0000 8.9685 4.0000 -1.0947 m. :
MEX , m C;
MATLAB. mex;
MEX m mex, C
. , ,
m MEX. (libmatlbmx).
m <matlab>\toolbox\matlab\elmat\invhilb.m ,
, . . m
MATLAB : : m m
mcc -x invhilb MATLAB.
, . MATLAB,
MATLAB. invhilb.dll -m, m C ,
: invhilb.c, invhilb.h, invhilb.m, invhilb_mex.c. .
MATLAB: ,
invhilb(10) . ANSI C C
.
MATLAB C/C++, MATLAB
1. UNIX MATLAB
.
Windows.
MATLAB, -p,
, MATLAB. UNIX
m C++ .
MATLAB ANSI C/++.
. ,
MATLAB Compiler.
,
. C C++,
5.1.2. mcc ,
MATLAB (mcc) m C. .
C m. . 5.1.1
, MEX, , C m.
(wrapper). , C++, ,
MATLAB, : MATLAB -m -p C
mex, . (wrapper) , C++.
mbuild.
. mbuild ANSI C.
MEX. MEX MATLAB matlab.h.
(dll), MATLAB. , matlab.h .
320 5. MATLAB 3.0 5.1. MATLAB 321
. 5.1.2. MATLAB
m C++ C.
(wrapper) .
. 5.1.2 , ,
, , -W
().
. 5.1.1. C)
5.1.2.
-I,
#W
. lib
Main -W main C/C++
. (.lib)
MEX -W mex MATLAB C mex)
: Library -W lib:libname C
1. MATLAB MFile Math Library (libmmfile). C++
2. MATLAB BuiltIn Library (libmatlb).
3. MATLAB MATFile Library (libmat). Simulink S)function -W simulink Simulink C mex)
4. MATLAB Application Program Interface Library (libmx). COM -W com:<componentname> COM
5. ANSI C Math Library (libm). [,<classname>[,<major>.
<minor>]]
-W comhg:<componentname>
. [,<classname>[,<major>.
<matlab>\extern\lib\win32\<compiler>. <minor>]]
Borland C++ Builder 7. Excel -W excel:<componentname> Excel
[,<classname>[,<major>.
<minor>]]
5.1.3. MATLAB -W excelhg:<componentname>
. 5.1.2 [,<classname>[,<major>.
MATLAB. <minor>]]
322 5. MATLAB 3.0 5.1. MATLAB 323
, C/C++ 5.1.4.
, . ,
C/C++ ( C/C++) MATLAB 3.0
, C/C++, MATLAB. , .
MATLAB 3.0 :
.
m m, ;
main.
MATLAB Java;
m func.m: m, input eval
function y = func(x) MATLAB;
x=input('x= ')
m, exist
y=sin(pi*x^2)*exp(1)^(3*x);
fprintf(1,f(x) = %1.4f,y); , exist("foo",'var');
m, ,
x, y
. :
. :
x= 'f';
mcc -m O none func
load('foo.mat',x);
func.c, func.h, func.exe
MATLAB (
func_main.c ( Glava_5\ Pr_5_05_1_ , eig, m,
C_Appl CD). func_main.c main. ). ,
, MATLAB (libmatlb).
MATLAB, . , .
: global persistent. :
if (y==3)
#ifndef MLF_V2 persistent x
#define MLF_V2 1 else
#endif x = 3;
end
#include "libmatlb.h" , mex,
#include "func.h" (
extern _mex_information _main_info;
MATLAB Compiler).
.
static mexFunctionTableEntry function_table[1] :
= { { "func", mlxFunc, 1, 1, &_local_function_table_func } }; MATLAB goto
if. Borland C++ goto
static _mexInitTermTableEntry init_term_table[1]
= { { InitializeModule_func, TerminateModule_func } };
try...catch. ,
-A debugline:on,
_mex_information _main_info try...catch. , if;
= { 1, 1, function_table, 0, NULL, 0, NULL, 1, init_term_table }; , Borland C++. m
, 8 9
/ *
, Borland
* The function "main" is a Compiler-generated main wrapper, suitable for
* building a stand-alone application. It calls a library function Error <file>.c <line>: Illegal octal digit in function
* to perform initialization, call the main function, and perform <functionname>
* library termination.
, Borland 009.0
*/
int main(int argc, const char * * argv) { , ,
return mclMain(argc, argv, mlxFunc, 1, &_main_info); ANSI C. ,
}
324 5. MATLAB 3.0 5.2. mbuild 325
, -t -L P
macro_option. :
mccstartup. , , ,
, mcc. MATLAB mbuild / mex.
mccstartup.
, 5.3.4.
. ,
\application data\mathworks\matlab\R13. C/C++,
mcc mccstartup . m ( . 5.5 ).
mccstartup, A ( ).
, mcc C/C++ . ,
. mccstartup -B . :
. m m / (annotation);
mcc, #line;
(<path> <file>) ,
"-I <path> <file>". , (debugline).
mcc -m /home/user/myfile.m m, C/C++
,
mcc -m -I /home/user myfile.m mcc -A annotation:type ...
, :
m , . all m ( )
(specified_file_mismatch), C/C++. m C/
. C++. all;
2. m, , m comments C/C++
, m . m, C/C++;
, MATLAB m MEX none , m.
, , MEX. #line,
, , MEX C/C++,
m.
mcc -A line:setting ...
m .
. , #line:
, . on #line C/C++
, ( , m.
COM, Excel COM, . .). ;
<matlab>/toolbox/compiler/bundles. off #line C/
-B . : C++. off.
B cpplib (C++). C++ .
B cpplib
-B csharedlib:<shared_library_name> -L cpp -T compile:lib mcc -A debugline:on ...
B csharedlib (C ). C :
. B csharedlib on
-t -W lib:<shared_library_name> -T link:lib -h libmmfile.mlib ;
B pcode (MATLAB). MATLAB (Pcode). off
B pcode . off.
336 5. MATLAB 3.0 5.3. mcc 337
-m MATLAB C %#function ,
, c , m.
, ( c mbuild.). %#external .
MATLAB C: m C C++.
main.c C mlfMain;
main.h mlfMain; m, C C++
mrank.c C mlfMrank; . , ,
mrank.h mlfMrank; C C++, MATLAB,
main_main.c main (main). C C++.
, mbuild , m
. C C++ .
, m , C m.
c: , C,
mcc -m main mrank m.
1. m
, ,
main.exe.
.
C++ -L cpp
1. m
C++ C.
C. ,
. m
mrank.m mrankwin.c (
m, MATLAB.
<matlab>\extern\examples\compiler\). mrank.m ,
,
1
. ,
n. mrankwin.c mrank
, mrank .
mcc -m main
, n
mrank, m 1 n.
main. , n, n = 12. ,
(Callback) <matlab>\extern\examples\compiler\ ,
feval ODE mrankp.c .
m, , .
. m .
. :
, mcc -t -W lib:Pkg -T link:exe -h mrank mrankwin.c libmmfile.mlib
(pragma) %#function. MATLAB C mrank.c, mrank.h
: mrank.m : pkg.c, pkg.h, pkg.exports pkg.mlib.
%#function <function_name-list> mbuild ,
. MATLAB, (mrank.c, Pkg.c, Pkg.h), C
() feval, eval (mrankwin.c) . ,
. , mcc, mbuild.
. mrankwin.c. ,
, mrank, mrank.m mlfMrank.
%#function. , , Pkg.
%#function, m /*
. * MRANKWIN
344 5. MATLAB 3.0 5.4. 345
mrankwin mlfMrank, , ,
N . .
R = mlfMrank(N); 1. file1.exports
mlfMrank mxArray * R. func1
R mlfPrintMatrix func2
MATLAB WinFlush();. file1.c
UNIX. double func1(double x)
UNIX Windows. {
return sin(2*x);
. mbuildopts.sh }
<matlab>/bin/mbuildopts.sh.
, , API double func1(double x)
{
C . return exp(x/2);
UNIX, . }
5.4.1. UNIX mbuild file1.c file1.exports
file1.dll. ,
HP700/HP)UX setenv SHLIB_PATH <matlab>/extern/lib/<arch>:$SHLIB_PATH file1.def, file1.lib file1.exp.
func1 func2.
IBM RS/6000 setenv LIBPATH <matlab>/extern/lib/ibm_rs:$LIBPATH , file1.dll ,
Borland C++ Builder.
setenv LD_LIBRARY_PATH <matlab>/extern/lib/ .
<arch>:$LD_LIBRARY_PATH :
//
UNIX //
(*.so) , (*.sl). TForm1 *Form1;
//
double (__stdcall *func1)(double);
C/C++ // ( DLL)
(SHLIB_PATH, LIBPATH LD_LIBRARY_PATH), HINSTANCE dllp;
. , __fastcall TForm1::TForm1(TComponent* Owner)
, : TForm(Owner)
. {
}
IBM_RS //
MATLAB C/C++. , ... ...
//
Digital UNIX, void __fastcall TForm1::FormCreate(TObject *Sender)
{
C++ Fortran. //
dllp = LoadLibrary("func1.dll");
// funk1 funk1
5.4.2. if (dllp) func1 =(double(__stdcall *) (double))GetProcAddress(dllp,
"_func1");
mbuild C }
//
UNIX, PC. mbuild, void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
, C {
. C //
FreeLibrary(dllp);
.exports. *.exports , }
348 5. MATLAB 3.0 5.4. 349
x, func1(x) func2(x)
func1 . Glava_5\Pr_5_04_1_CLib :
. function y = fun3(x)
2. m x=input('x= ')
. m y=func1(x);
z=func2(x);
function y = func1(x) fprintf(1,Ans = %1.4f %1.4f ',y, z);
y = sin(pi*x);
function y = func2(x) fun3 mlib,
y = exp(1)^(x/2); mcc -m fun3
MATLAB func1 func2
mylib.dll func1.m func2.m . -h, m ( ,
: ).
mcc -W lib:mylib -L C -t -T link:lib -h func1 func2 mlib,
, mcc -m -O none fun3 mylib.mlib
MATLAB Lcc, Borland C++ Builder. : func1 func2 mylib.dll.
-t C , .
m; mlib ,
-T link:lib ,
; .
-h m, fun3.exe mylib.dll.
mcc, Glava_5\Pr_5_04_2_CLib CD.
. 3. Borland C++ Builder.
, m func1.m func2.m, func1(x) func2(x) mylib.dll
: , Borland C++ Builder.
mylib.dll ; :
mylib.c ; 1. , func1 func2, MATLAB
mylib.h C ; m,
mylib.def ; Borland C++ Builder
mylib.exports mylib.exp ; MATLAB. MATLAB
mylib.mlib . 7.
, 2. mylib.h.
func1.c, func1.h, func2.c, func2.h. 3. mylib.lib.
Glava_5\Pr_5_04_2_CLib CD. . , lib, MATLAB,
Glava_5\ Pr_5_04_6_CShLib. Borland C++ Builder.
mylib.c. (mylibInitialize) COFF OMF coff2omf.
(mylibTerminate) . libtimefunInitialize . mylib.lib
, def implib (
. Borland C++ Builder).
, C, def , .
. mylibTerminate ASCII .
, . .
mlib. mylib.mlib mylib.def:
mylib.dll. LIBRARY mylib.dll
. , fun3.m, EXPORTS
350 5. MATLAB 3.0 5.4. 351
5.4.3. 5.5.
Windows , MATLAB, ,
, : .
; : ,
, , bin, mbuild , C C++ , ,
, . m , m C/
, mbuild bin C++ , C/C++ m.
;
MEX, 5.5.1.
;
MATLAB, . MATLAB m :
MATLAB , C C++ , (-L);
, ;
mglinstaller.exe, , W.
MATLAB. C C++ , ,
, ,
. , .
mglinstaller.exe MATLAB , .
<matlab>\extern\lib\win32\mglinstaller.exe. .
. . 5.5.1 , m
: (file.m) MEX, .
MATLAB.
5.5.1.
, . C C++
; file.h file.hpp
PATH bin/<ARCH>, file.c file.cpp
MATLAB. Main ()W main) file_main.c file_main.cpp
, Mex ()W mex) file_mex.c
MATLAB, Simulink ()W simulink)
. file_simulink.c
()W lib:file) file.c file.cpp
.
file.h file.hpp
, . file.exports file.mlib
DOS : file.mlib
The ordinal #### could not be located in the dynamic-link library
dforrt.dll. m func.m
, function y = func(x)
dforrt.dll dformd.dll Windows x=input('x= ')
354 5. MATLAB 3.0 5.5. 355
mclMpower(mlfScalar(svDoubleScalarExp(1.0)), 5.5.2.
mclMtimes(mlfScalar(3), mclVa(x, "x")))));
/* C C++
* fprintf(1,Ans = %1.4f,y); func mlfFunc func func.c
*/ mlxFunc Nfunc func.h
mclAssignAns(&ans, mlfNFprintf(
mlNFunc Vfunc func.cpp
0, mlfScalar(1), mxCreateString("Ans = %1.4f"), mclVv(y, "y"),
NULL)); mlfNFunc mlxFunc func.hpp
mclValidateOutput(y, 1, nargout_, "y", "func"); mlfVFunc
mxDestroyArray(ans);
mxDestroyArray(x); C
mclSetCurrentLocalFunctionTable(save_local_function_table_);
Mf .
return y;
} ,
func_main.c, , m.
. mlxF . mlxF
, feval.
#ifndef MLF_V2
#define MLF_V2 1 feval, ,
#endif feval. C
feval (mlxFunc) func.m,
#include "libmatlb.h"
#include "func.h"
. C Mfunc.
/*
extern _mex_information _main_info; * "mlxFunc" feval
* m- "func" "d:\pr_5_05_1_c\func.m" ( 1-5).
static mexFunctionTableEntry function_table[1] * feval func .
= { { "func", mlxFunc, 1, 1, &_local_function_table_func } }; *
* .
static _mexInitTermTableEntry init_term_table[1] */
= { { InitializeModule_func, TerminateModule_func } }; void mlxFunc(int nlhs, mxArray * plhs[], int nrhs, mxArray * prhs[])
{
_mex_information _main_info mxArray * mprhs[1];
= { 1, 1, function_table, 0, NULL, 0, NULL, 1, init_term_table }; mxArray * mplhs[1];
int i;
/* /* */
* The function "main" is a Compiler-generated main wrapper, suitable for if (nlhs > 1)
* building a stand-alone application. It calls a library function to {
perform mlfError(mxCreateString(
* initialization, call the main function, and perform library termination. "Run-time Error: File: func Line: 1 Column: 1
*/ The function \"func\"" " was called with more
int main(int argc, const char * * argv) { than the declared number of outputs (1)."), NULL);
return mclMain(argc, argv, mlxFunc, 1, &_main_info); }
} if (nrhs > 1)
{
mlfError(
5.5.2. mxCreateString(
"Run-time Error: File: func Line: 1 Column: 1
m ++, The function \"func" "\" was called with more
m, (. than the declared number of inputs (1)."), NULL);
}
func.c), . for (i = 0; i < 1; ++i) {mplhs[i] = NULL;}
, for (i = 0; i < 1 && i < nrhs; ++i){mprhs[i] = prhs[i];}
( ). m for (; i < 1; ++i) {mprhs[i] = NULL;}
func.m, mlfEnterNewContext(0, 1, mprhs[0]);
. 5.5.2: /* */
358 5. MATLAB 3.0 5.5. 359
mplhs[0] = Mfunc(nlhs, mprhs[0]); //
mlfRestorePreviousContext(0, 1, mprhs[0]); // "mlxFunc" feval m- "func"
plhs[0] = mplhs[0]; // "d:\pr_5_05_1_cpp\func.m" ( 1-5).
} // feval func .
//
mlfF . mlfF // .
, "" C . //
C (mlfFunc) void mlxFunc(int nlhs, mxArray * plhs[], int nrhs, mxArray * prhs[])
, . C Mfunc: {
MW_BEGIN_MLX();
/* {
* "mlfFunc" m- "func" mwArray mprhs[1];
* * "d:\pr_5_05_1_c\func.m" ( 1-5). mwArray mplhs[1];
* int i;
* . mclCppUndefineArrays(1, mplhs);
*/ if (nlhs > 1) {
mxArray * mlfFunc(mxArray * x) error(
{ mwVarargin(
int nargout = 1; mwArray(
mxArray * y = NULL; "Run-time Error: File: func Line: 1 Column: 1"
mlfEnterNewContext(0, 1, x); "The function \"func\" was called with more "
y = Mfunc(nargout, x); "than the declared number of outputs (1).")));
mlfRestorePreviousContext(0, 1, x); }
return mlfReturnValue(y); if (nrhs > 1) {
} error(
mwVarargin(
mlfNF . mwArray(
, m nargout. nargout "Run-time Error: File: func Line: 1 Column: 1"
int "The function \"func\" was called with more "
"than the declared number of inputs (1).")));
nargout, , }
NULL for (i = 0; i < 1 && i < nrhs; ++i) {
. mprhs[i] = mwArray(prhs[i], 0);
mlfVF . }
for (; i < 1; ++i) {
, m nargout mprhs[i].MakeDIN();
. void }
, mplhs[0] = Mfunc(nlhs, mprhs[0]);
plhs[0] = mplhs[0].FreezeData();
( MATLAB }
ans), . MW_END_MLX();
C++ . C++ }
. F . F
++ func.m, , "" C++ .
. func.cpp, func.hpp, func.exe func_main.cpp ( C++
Glava_5\Pr_5_05_2_Cpp_Appl (func.m):
CD). //
// "Mfunc" m-
mlxF . C++ mlxF // "func" "d:\pr_5_05_1_cpp\func.m"( 1-5).
C, feval C // -.
C++. mlxF , //
// , .
feval. C++ feval
//
(mlxFunc) func.cpp. // function y = func(x)
C++ Mfunc. //
360 5. MATLAB 3.0 5.5. 361
mylib.h C ;
mylib.def ; . , .
mylib.exports mylib.exp ; ,
mylib.mlib . -O none -g.
(mylibInitialize) .
(mylibTerminate) . mylibInitialize .
, ,
. mcc -xg gasket
, C, 80 :
. mylibTerminate , , m
. .
,
m. ,
-F <option>
C.
mylib.mlib
mylib.dll. mlib . mcc -F list ...
5.4.2. . n
2. , COM ( ) , page-width:n.
, . MATLAB Compiler, MATLAB Excel Builder MATLAB 80 . n
COM Builder. ,
mbuild . regsvr mbuild . , , ,
mwregsvr32 . 40:
. mcc -xg -F page-width:40 gasket
, COM. .
<filename>.idl. IDL , n, statement-indent:n.
mbuild. MIDL 4 .
. .idl , expression-indent:n.
mbuild. , n, 2 .
<filename>.def. DEF , ,
mbuild, , , :
. def . mcc -F statement-indent:2 -F expression-indent:1 -xg gasket
<filename>.rc. RC
m .
MATLAB, DLL .
C
.rc .
C++ . /
. /++
m() , *line.
, MATLAB,
. ,
-A <option>
.
/++ . .
annotation:type.
m C C++ .
5.5.4. type:
all m (
C C++ . ), C/C ++ ;
364 5. MATLAB 3.0 5.5. 365
comments m; .
none m C/C ++ . , , .
, tmmult.m -A debugline:on:
all, m mcc -x -A debugline:on tmmult
( ), C/C ++ . :
. ??? Error using ==> tmmult
(Pr_5_05_1_C_Appl). Error using ==> *
#line . Inner matrix dimensions must agree.
#line C/C++, C/C++ Error in File: "<matlab>\extern\examples\compiler\tmmult.m",
Function: "tmmult", Line: 4.
( MATLAB),
(m). #line, 5.5.5.
m. C
m. #line %#external, %#function
, . ., m. %#mex C/C++ m,
#line C C++ feval MEX.
line:setting. setting: %#external. MATLAB
on #line; C/C++ m.
off #line. m ( ),
, m,
line,
C C++. C (
off,
. MATLAB Compiler).
#line C/C++ . ,
, C,
#line page-width ,
. m
C .
#line C C++ . ,
: , . C measure_from_device(),
double. collect.m
mcc -A line:on ...
m :
.
function collect
y = zeros(1, 100); %
debugline:setting. for i = 1:100
setting: on off. off, y(i) = collect_one;
end
. , m
function y = collect_one
tmmult.m, MATLAB : Inner matrix
dimensions must agree. persistent t;
function tmmult if (isempty(t))
a = ones(2,3); t = 0;
b = ones(4,5); end
t = t + 0.05;
y = mmult(a,b) y = sin(t);
5.6.
(), .
3.0 MATLAB , , ,
. .
. , :
. , function y = foo(x)
, . y = 2*pi*x;
, O none, :
. , ...
, mlfAssign(&y, mclMtimes(mlfScalar(6.283185307179586),
. mclVa(x, "x")));
, , ...
. O fold_scalar_mxarrays:on, :
. ...
mlfAssign(&y, mclMtimes(_mxarray0_, mclVa(x, "x")));
...
-O all
<matlab>/toolbox/compiler/bundles/
_mxarray0_,
opt_bundle_all. (
2*pi.
speculate),
mxArray .
-g .
. (fold_non_scalar_mxarrays)
.
fold_scalar_mxarrays.
mxArray ,
-O none
. ,
<matlab>/toolbox/compiler/bundles/ [] {} .
opt_bundle_none. . , , :
-g . function y = test
. y = [ 1 0; 0 1] * [ pi pi/2; -pi -pi/2 ];
-O none, :
-O list ...
. mlfAssign(&y, mclMtimes(mlfDoubleMatrix(2, 2, _array0_, (double *)NULL),
, : mlfDoubleMatrix(2, 2, _array1_, (double *)NULL)));
...
-O <optimization option>:[on|off]
-O fold_non_scalar_mxarrays:on,
<optimization option> : :
array_indexing ; ...
fold_mxarrays ; mlfAssign(&y, _mxarray4_);
fold_non_scalar_mxarrays ; ...
fold_scalar_mxarrays ; _mxarray4_ , [ 1 0; 0 1] *
optimize_conditionals ; [pi pi/2; -pi -pi/2 ].
optimize_integer_for_loops ; . (fold_mxarrays)
percolate_simple_types ; fold_scalar_mxarrays fold_non_scalar_mxarrays.
speculate . P.
. . (array_
. (fold_scalar_ indexing)
mxarrays), .
370 5. MATLAB 3.0 5.5. 371
, {
int v_ = mclForIntStart(1);
. int e_ = mclLengthInt(mclVa(x, "x")) - 1;
. , : if (v_ > e_) {
function y = test(x,i1,i2); mlfAssign(&i, _mxarray0_);
y = x(i1,i2); } else {
...
O none, : for (; ; ) {
... ...
mlfAssign( if (v_ == e_) { break; }
++v_;
&y,
}
mlfIndexRef(mclVa(x, "x"), "(?,?)", mclVa(i1, "i1"),
mlfAssign(&i, mlfScalar(v_));
mclVa(i2, "i2")));
}
... ...
O array_indexing:on : . (optimize_
... conditionals) MATLAB
mlfAssign(
&y, mclArrayRef2(mclVa(x, "x"), mclVa(i1, "i1"),
C, ,
mclVa(i2,"i2"))); . "", nargin, nargout
... for ( )
mclArrayRef2 . . , :
mclArrayRef . function test(a,b,c,d)
. (optimize_integer_for_loops) if (nargin < 4)
d = 0.0;
, . end
,
-O none :
C . ,
...
C
if (mlfTobool(mclLt(mlfScalar(nargin_), mlfScalar(4)))) {
m. ...
. : -O optimize_conditionals:on :
function test(x)
...
for i = 1:length(x)-1
if (nargin_ < 4) {
x(i) = x(i) + x(i+1)
...
end
-O none, : MATLAB. (percolate_simple_
types) ()
...
{ (double) , .
mclForLoopIterator viter__; , sin(v) , v
for (mclForStart( double , double
&viter__,
mlfScalar(1), sin. C/C++
mclMinus(mlfLength(mclVa(x, "x")), . P.
mlfScalar(1)), NULL); . (speculate)
mclForNext(&viter__, &i);
) { , MATLAB
... double. MATLAB
} .
mclDestroyForLoopIterator(viter__);
} .
...
-O optimize_integer_for_loops:on :
...
6.1. 373
, . MATLAB
, ANSI C C++,
MATLAB 7. 32
C/C++,
Windows (DLL) Windows NT:
6. MATLAB 4 Lcc C 2.4 ( MATLAB). C
C++;
.
Borland C++ 5.3, 5.4, 5.5, 5.6 ( Borland
, 4 MATLAB (
C++ Builder 3.0, 4.0, 5.0, 6.0.);
MATLAB R14 ).
Microsoft Visual C/C++ (MSVC) 6.0, 7.0 7.1.
. MATLAB
MATLAB, . 4 MATLAB MATLAB ANSI C C++ Linux :
MATLAB (toolboxes). GNU C, gcc;
MATLAB ANSI C;
: GNU C++, g++.
, , MATLAB MATLAB ,
; . MATLAB
C C++ , MATLAB Compiler.
MATLAB ; . MATLAB MATLAB
Excel (Excel addins), MATLAB Builder Excel; MATLAB.
COM(COM objects), MATLAB Builder COM. MATLAB :
. Web MATLAB Compiler product. , MATLAB,
MATLAB ;
. ,
C C++. , ;
4 MATLAB Symbolic Math Toolbox
, , .
MATLAB, .
MATLAB . http://
m,
www.mathworks.com/products/compiler/compiler_support.html. ,
14 MATLAB.
,
. :
6.1. , MATLAB;
MATLAB. Simulink;
, MATLAB;
Windows Microsoft Linux. clc, home savepath.
, , ,
MATLAB Compiler.
MATLAB.
:
Lcc C C++;
6.1.1. , COM
4 MATLAB, Excel, Microsoft Visual C/C++ (
MATLAB 7 ( 14). 6.0, 7.0 7.1);
374 6. MATLAB 4 6.1. 375
6.1.4. 4 , m. ,
example.m,
a filename filename , , mcc -m example
CTF example.exe.
l , . . C
( 13) m -l. :
N
mcc -l file1.m file2.m file3.m
p <directory> libfile1.dll Windows libfile1.so
. )N Linux. -l ,
R -nojvm ; MCR -W lib -T link:lib
R -nojit -W lib
libfile1. -T link:lib
.
6.1.3. MATLAB . .
MATLAB MATLAB Builder for COM. MATLAB Builder for COM
, , COM (Addin) m COM,
Excel. . , COM.
. MATLAB (mcc) m MATLAB Builder for Excel. MATLAB Builder for Excel
, . Visual Basic Application file (.bas)
(plugin DLL) m MATLAB,
,
Excel .
.
. 6.2.
: , MATLAB.
; , ,
, , , MATLAB
, , MATLAB mcc.
(MCR);
, 6.2.1. MATLAB
MCR.
4 ,
, main. MATLAB Component Runtime (MCR),
m. MCR
(public) m. MATLAB.
. 4
CTF, MATLAB, (Component Technology File, CTF) ,
: , CTF MATLAB (m, MEX),
. . m CTF,
. (AES),
. MATLAB RSA 1024 . ,
-m m , MATLAB, CTF.
. C C++ CTF,
MCR, m, .
380 6. MATLAB 4 6.2. 381
m . .
CTF CTF. , MEX P,
m CTF m. m, ,
. , . .
, CTF. MATLAB.
m, . CTF, ,
m CTF. ,
MATLAB MATLAB (m MEX),
. , .
MATLAB, m, . . ,
: .
; .
; , , :
; C/C++ m,
; (foo_main.c).
. ;
. 6.2.1 , m (foo_mcc_component.dat),
. , m
. ,
m, CTF
.
C/C++. C/C++
.
().
MATLAB,
. C/C++
mbuild MATLAB.
6.2.2. , mcc
, .
.
4 m, foo.m bar.m,
foo.exe .
mcc -m foo.m bar.m
:
foo_main.c C main. main
, ,
foo;
foo_mcc_component_data.c C , ,
MCR, .
,
. 6.2.1. MCR;
382 6. MATLAB 4 6.2. 383
M . . R:
mcc -m -R "-nojvm -nojit" -v foo.m
-M string mcc -m -R "-nojvm" -v -R "-nojit" foo.m
mcc -m -R -nojvm -R -nojit foo.m
string mbuild. mcc -m -R -nojvm -v foo.m
, -M mcc -m -R -nojvm -R -nojit foo.m
"-Dmacro=value". -M , :
-M.
mcc -m -R -nojvm -nojit foo.m
N . -N
, ( ): T . .
<matlabroot>/toolbox/matlab
<matlabroot>/toolbox/local -T target
<matlabroot>/toolbox/compiler . target :
. codegen C/C ++ .
. codegen;
o . compile:exe , codegen, C/C++
( ). ,
;
-o outputfile compile:lib , codegen, C/C++
. ,
(, .exe Windows). /DLL;
p . link:exe , compile:exe
, , ;
MATLAB: link:lib , compile:lib,
-p directory /DLL.
directory , . directory v . ,
, . , ,
:
, mbuild.
, -p, MATLAB
w . .
, ,
, .
, -p, -w option[:<msg>]
MATLAB, ( . :
-I, ). w list , <string>
R RunTime. -R , enable, disable error.
MCR . ;
-R option w enable ;
. w disable[:<string>] ,
option: <string>. .
-nojvm Java (JVM); <string>.
-nojit MATLAB JIT ( :<string> disable ;
m). w enable[:<string>] ,
-R . <string>. .
MCR MATLAB, <string>. :<string>
mclInitializeApplication mclTerminateApplication. enable ;
390 6. MATLAB 4 6.3. mcc 391
w error[:<string>] , / ,
<string>, . :<string> liba a0.m and a1.m:
error . mcc -W lib:liba -T link:lib a0 a1
W . .
-W type
mcc. .
(),
m. , :
.
mcc -m -g myfun mcc -mg myfun
:
, ,
main POSIX main();
lib:<string> . , :
mcc -v -W main -T link:exe myfun
mcc -vW main -T link:exe myfun
.
:
,
mcc -Wv main -T link:exe myfun
m. <string>
C/C++ . .exports,
; ,
com:<component_name>, <class_name>, <version> COM , . , ,
m; :
none . none. mcc -m -W none test.m
mcc -W main -T link:exe -W none test.m
Y . license.dat
-W.
.
, -W none
-Y license.dat_file
. ,
z .
. .
-z path , mccstartup.
path , mcc,
, , matlabroot. mccstartup. ,
? . MATLAB. .
:
;
myfun.m: <system root>\profiles\, <user>\
mcc -m myfun application data\mathworks\matlab\R14.
myfun.m. myfun.m / mcc mccstartup
files/source C . mcc mccstartup,
/files/target: , ,
mcc -m -I /files/source -d /files/target myfun mcc . mccstartup
myfun1.m myfun2.m ( -B .
mcc): . ,
mcc -m myfun1 myfun2 , .
392 6. MATLAB 4 6.3. mcc 393
. -B.
, . ,
, . . , csharedlib C
.
-W lib:%1% -T link:lib
6.3.2. mcc C
mcc -B csharedlib:mysharedlib myfile.m myfile2.m
-l macro_option_l -W lib -T link:lib , %n%
, mcc ( %1%
-m macro_option_m C -W main -T link:exe mysharedlib).
1. -B
DOS, UNIX. -B MATLAB
, , , m: , -B , ,
-W main ; . :
-T link:exe . mcc -B csharedlib:libtimefun weekday data tic calendar toc
, MATLAB , libtimefun
macro_option, <matlabroot>/toolbox/compiler/bundles. . ,
, -m, . , cexcel
macro_option_m. -W excel:%1%,%2%,%3% -T link:lib b,
. m %1%,%2%,%3%. DOS :
mcc, MATLAB : mcc -B 'cexcel:component,class,1.0' weekday data tic calendar to
(<path> <file>)
. <matlab>\
"I <path> <file>". : toolbox\compiler\bundles\ . 6.3.3.
mcc -m /home/user/myfile.m
6.3.3. 4
mcc -m -I /home/user myfile.m
, ccom COM -W com:<component_name>,
. -v <class_name>,
, m . -v <version> -T link:lib
m . , cexcel Excel COM -W excel:<component_name>,
(specified_file_mismatch), <class_name>,
. <version> -T link:lib -b
cppcom COM -B ccom:<component_name>,
<class_name>, <class_name>,
6.3.2. <version>
cppexcel Excel COM -B cexcel:<component_name>,
<class_name>,<version>
MATLAB . cpplib C++ -B csharedlib:<shared_library_name>
: -T compile:lib
-B <filename>[:<a1>,<a2>,...,<an>] csharedlib C -W lib:<shared_library_name>
-T link:lib
mcc,
B . macro_option_l )l -W lib -T link:lib
mcc / macro_option_m )m -W main -T link:exe
394 6. MATLAB 4 6.3. mcc 395
, m , for k = 1:n
r(k) = rank(magic(k));
. MATLAB.
end
, , m ,
. main.m main, mrank
MATLAB m , .
m . function main
r = mrank(5)
. function
m. ,
m . , MATLAB:
, , mcc -mc main mrank
C C++. -c mcc -mc main mrank mbuild.
m. -m MATLAB C,
m, mcc. . , MATLAB
m :
m, . main_main.c C,
, . main;
main.ctf , , MATLAB (m
6.4. , MEX), .
, .
, MATLAB
mrank.m main.m, ,
.
. ,
, MATLAB,
MATLAB.
;
C m,
main_mcc_component_data.c , MCR,
m, MEX C
. ,
C++. MATLAB m C
MCR.
, m MATLAB.
C , mbuild
(runtime libraries). . -c mcc,
mbuild:
6.4.1. m, mcc -m main mrank
, main_main.c, main.ctf main_mcc_ component_ data.c,
,
main.exe.
m, MEX.
m
3. ,
MATLAB.
. .
1. ,
, main.ctf,
m: mrank.m main.m (
<matlab>\extern\examples\compiler\). C main_mcr (
m. ).
mrank.m r m MATLAB,
1 n. , r(3) mrank.m main.exe. , main_mcr
33: 268 28 1,47 .
function r = mrank(n)
Glava_6\Pr_6_4_mrank
r = zeros(n,1); CD.
398 6. MATLAB 4 6.4. 399
6.4.2. , C C++
,
m ,
C C++.
, m C C++
.
1.
, ,
.
2. m C. ,
mrankp.c,
, mrank.m printmatrix.m.
<matlabroot>\extern\examples\compiler\.
mrankp.c m
. :
mcc -W lib:libPkg -T link:exe mrank printmatrix mrankp.c
mrankp.c, printmatrix.m mrankp.c
, . MATLAB
, mrank.exe, C
:
. 6.4.1. m) C
libPkg.c
libPkg.ctf
libPkg.h mrankp.c. mrankp.c mrank ,
libPkg_mcc_component_data.c mrank.
libpkg.exports
Glava_6\ #include <stdio.h>
Pr_6_4_mrank_P Glava_6\ Pr_6_4_mrank_W CD. #include <math.h>
mbuild #include "libPkg.h"
C (mrankp.c) main( int argc, char **argv )
. {
mlfMrank mlfPrintmatrix m mrank.m printmatrix.m, mxArray *N; /* , n */
mxArray *R = NULL; /* */
. int n; /* */
mrank.exe,
/* n */
1 12. mrank.exe /* , n=12 */
libPkg_mcr, m dll, if (argc >= 2) {
mrank.exe ( libPkg.ctf). n = atoi(argv[1]);
} else {
MATLAB mrankp.c : n = 12;
<matlabroot>/extern/examples/compiler. mrankp.c mrankwin.c. }
mrankp.c POSIX main, mlfMrank, mclInitializeApplication(NULL,0);
libPkgInitialize(); /* M- */
m mrank.m,
mlfPrintmatrix, m printmatrix.m. /* 1--1 n */
N = mxCreateScalarDouble(n);
mrankwin.c Windows mrankp.c, WinMain
mlfMrank mlfPrintmatrix. /* mlfMrank, mrank.m. */
400 6. MATLAB 4 6.4. 401
, Linux .
. ,
, , :
. -p , setenv LD_LIBRARY_PATH
, MATLAB. : <matlabroot>/bin/glnx86:
p <directory> <matlabroot>/sys/os/glnx86:
<matlabroot>/sys/java/jre/glnx86/jre1.4.2/lib/i386/client:
<directory> , . <directory> <matlabroot>/sys/java/jre/glnx86/jre1.4.2/lib/i386:
, , . <matlabroot>/sys/opengl/lib/glnx86:${LD_LIBRARY_PATH}
, -p -N mcc. setenv XAPPLRESDIR <matlabroot>/X11/app-defaults
DOS UNIX.
6.4.4. .
.
, m, .
, , , m Windows :
, m .
MCRInstaller.exe
, , m:
MATLAB Component Runtime library.
m, MEX P.
<matlabroot> \toolbox\compiler\deploy\win32;
, ,
m, , libPkg.ctf Component Technology File (ctf);
, feval ODE. mrank.exe .
. Linux. MCR
, , .
, , buildmcr;
%#function. MCRInstaller.zip
3. %#function, <matlabroot>/toolbox/compiler/deploy/<arch>.
m ,
MCRInstaller filename path,
-a.
,
buildmcr(path, filename);
%#function, m
, :
feval, fminbnd, fminsearch, funm, fzero ODE. MCRInstaller.zip
, , MATLAB Component Runtime library.
Callback fcn m. ;
unzip MCRInstaller.zip;
6.4.5. , libPkg.ctf Component Technology File (ctf).
;
, mrank.exe. mrank .
,
. , .
, .
. , CTF
. -a .
. , MCR.
. Windows MCRInstaller.exe . ,
: C:\MCR C:\MCR. MCRInstaller
<matlabroot>\bin\win32 .
404 6. MATLAB 4 6.5. 405
Windows. MCR ,
c:\Program Files\MathWorks\MATLAB Component Runtime\, MATLAB.
MCR 260 .
CTF 6.5.1. C
, , C:\approot,
mcc, C C++
: <mcr>\v71\runtime\win32. <mcr> ,
.
MCR. Windows XP,
. C . -W lib
, CTF. C m
, m MEX. . MATLAB ,
. CTF .
, . , m. ,
, extractCTF, C .
<matlabroot>/toolbox/compiler/deploy/<ARCH> , <ARCH> 1. ,
win32 Windows glnx86 Linux. CTF -W lib -W cpplib,
. , , . .
libMultpkg.ctf : 1. C
extractCTF.exe libMultpkg.ctf m. matrixdriver.c
libMultpkg_mcr. , .
, , <componentname>_mcr,
componentname CTF . MATLAB <matlabroot>/extern/examples/compiler :
Linux . addmatrix.m, multiplymatrix.m, eigmatrix.m matrixdriver.c.
MCR (MCRInstaller.zip) , 2. matrixdriver.c main
<mcr_root>. <mcr_root>, <matlabroot>, , mlfAddmatrix.
<matlabroot>. addmatrix.m, multiply
CTF , /home/<user>/approot. matrix.m eigmatrix.m :
. mcc -B csharedlib:libmatrix addmatrix.m multiplymatrix.m eigmatrix.m -v
, . :
setenv LD_LIBRARY_PATH -B csharedlib ,
<mcr_root>/runtime/glnx86: -W lib:<libname> -T link:lib
<mcr_root>/sys/os/glnx86:
<mcr_root>/sys/java/jre/glnx86/jre1.4.2/lib/i386/client: -W lib:<libname> MATLAB
<mcr_root>/sys/java/jre/glnx86/jre1.4.2/lib/i386: libname;
<mcr_root>/sys/opengl/lib/glnx86:${LD_LIBRARY_PATH} -T link:lib
setenv XAPPLRESDIR <matlabroot>/X11/app-defaults
.
,
: libmatrix.c, libmatrix.h,
. MATLAB,
libmatrix_mcc_component_data.c, libmatrix.ctf, libmatrix.exp, libmatrix.exports,
<mcr_root> .
libmatrix.lib libmatrix.dll.
MATLAB matlabroot .
Glava_6\Prim_6_5_matrix_Lib CD.
mrank.exe
.
.
MATLAB ,
:
6.5. 1.
MATLAB C <libname>.h.
C++ . C C++, 2. .
406 6. MATLAB 4 6.5. 407
. . MCR
, , (MCR instance), .
. , <matlabroot>\bin\win32 ,
. , MATLAB, MCR,
: . MCR,
matrixdriver.exe MCR. MCR .
: MCR MCR .
The value of the added matrix is:
MCR MCR.
2.00 4.00 6.00
8.00 10.00 12.00 :
14.00 16.00 18.00 mclInitializeApplication
mclTerminateApplication
The value of the multiplied matrix is:
30.00 36.00 42.00 mclInitializeApplication
66.00 81.00 96.00 MCR. MCR.
102.00 126.00 150.00 MCR.
:
The eigenvalue of the first matrix is:
16.12 -1.12 -0.00 bool mclInitializeApplication(const char **options, int count);
bool mclTerminateApplication(void);
,
4. mclInitializeApplication
.
.
:
MathWorks.
MCRInstaller.zip (Linux) MATLAB Component
mclInitializeApplication.
Runtime;
( , mcc
MCRInstaller.exe (Windows) MATLAB Component
R) ( ). true
Runtime.
false .
unzip (Linux) MCRInstaller.zip;
mclTerminateApplication.
matrixdriver.ctf Component Technology File.
, MCR .
;
true false .
matrixdriver (matrixdriver.exe Windows);
, mclTerminateApplication
libmatrix .
mclInitializeApplication. MathWorks
, DLL Windows.
mclTerminateApplication.
,
.
, :
6.5.2. C++,
MCRInstaller.zip (Linux) MATLAB Component C++
Runtime; m. MATLAB
MCRInstaller.exe (Windows) MATLAB Component .
Runtime; m.
unzip MCRInstaller.zip; 5. ,
matrixdriver.ctf Component Technology File. -W lib -W cpplib,
; .
libmatrix . 2. C++ .
, DLL Windows; C ,
libmatrix.h . C++. C++ m
410 6. MATLAB 4 6.5. 411
. , .
void <function-name>(int number_of_return_values, ,
<list_of_return_variables>, <list_of_input_variables>); , .
<list_of_input_variables> extern void mlfAddmatrix(int nargout, mxArray** a, mxArray* a1,
const mwArray&, <list_of_return_variables> mxArray* a2);
mwArray&. , libmatrix C++ ,
m addmatrix . ( mx
void addmatrix(int nargout, mwArray& a , const mwArray& a1, DestroyArray), , .
const mwArray& a2); , ,
. C++ m .
. mwException. , , mlf,
mwExceptions what() , mlx.
. :
C++ trycatch. mlfAddmatrix(1, &out, in1, in2);
try mlf (non
{ NULL), mlf ,
.
(call function) mxDestroyArray. ,
. mlf,
} . , NULL
catch (const mwException& e)
{ MATLAB ,
. ,
(handle error) ()
.
} . ,
matrixdriver.cpp .
C++.
6.5.4. varargin
6.5.3. , m, varargout m,
m, MATLAB, m varargin varargout,
: mlx mlf. . , N varargin,
( m). 1N. varargout
. . varargout ,
m. ,
. . , m.
mlx . , mlx,
[a,b,varargout] = myfun(x,y,z,varargin)
, MEX MATLAB (.
MEX). , nlhs, C :
, , plhs, , void mlfMyfun(int numOfRetVars, mxArray **a, mxArray **b,
mxArray **varargout, mxArray *x, mxArray *y,
. mxArray *z, mxArray *varargin)
, .
varargout (numOfRetVars 2), 2
extern void mlxAddmatrix(int nlhs, mxArray *plhs[],
int nrhs, mxArray *prhs[]);
, a b.
mlf .
mlf. ,
7.1. , 415
#include <vcl.h> .
#pragma hdrstop . ,
418 7. 7.1. , 419
() , };
//
. extern PACKAGE TForm1 *Form1;
TForm1 . //-
Unit_71.h, . #endif
Unit_71.h: .
//- 8 ( ),
#ifndef Unit_71H . Edit1 Edit2
#define Unit_71H
//- () ( ). (
#include <Classes.hpp> 8) , .
#include <Controls.hpp> , . ,
#include <StdCtrls.hpp> NCh0 mwArray ,
#include <Forms.hpp>
#include <Dialogs.hpp> StrToInt(Edit1->Text).
#include <Menus.hpp> //
#include <ExtCtrls.hpp> //
//-
class TForm1 : public TForm void __fastcall TForm1::Edit1Change(TObject *Sender)
{ {
__published: // IDE-managed Components NCh0 = StrToInt(Edit1->Text);
TMainMenu *MainMenu1; }
TOpenDialog *OpenDialog1; // -
TSaveDialog *SaveDialog1; void __fastcall TForm1::Edit2Change(TObject *Sender)
TMenuItem *N1; {
TMenuItem *N2; NLen0 = StrToInt(Edit2->Text);
TMenuItem *N3; }
TGroupBox *GroupBox1;
TEdit *Edit1;
.
TLabel *Label1; . NCh0 NLen0 mwArray
TEdit *Edit2; iNCh0 iNLen0 int if,
TLabel *Label2; , : NCh0 = 8,
void __fastcall Edit1Change(TObject *Sender);
void __fastcall Edit2Change(TObject *Sender); NLen0 = mclGetInf() . mode
void __fastcall N2Click(TObject *Sender); "rt" . file
void __fastcall N3Click(TObject *Sender); . v.
void __fastcall FormCreate(TObject *Sender);
private: // User declarations MATLAB fscanf %g
public: // User declarations . ,
__fastcall TForm1(TComponent* Owner); Edit1 Edit2
.
mwArray NCh0; //
mwArray NLen0; // void __fastcall TForm1::N2Click(TObject *Sender)
{
mwArray NCh; // if(OpenDialog1->Execute())
int iNCh; // {
int iNCh0 = NCh0.ExtractScalar(1); // mwArray
mwArray NLen; // int iNLen0 = NLen0.ExtractScalar(1);
int iNLen; //
if (iNCh0 == 0) {NCh0 = 8;}
mwArray Sig; // if (iNLen0 == 0) {NLen0 = mclGetInf();}
mwArray DOut; //
mwArray Y; mwArray mode("rt");
mwArray SigDt; mwArray file(OpenDialog1->FileName.c_str());
mwArray MaxY;
mwArray MinY; //
420 7. 7.2. mwArray 421
mwArray v; }
v = fopen(file, mode); //-
Sig = fscanf(v, "%g ", horzcat(NCh0, NLen0));
fclose(v); . DOut,
.
mwArray sizeSig = size(Sig); // ,
NCh = sizeSig(1); //
NLen = sizeSig(2); //
. mode "wt"
. file .
iNCh = sizeSig.ExtractScalar(1); fid.
iNLen = sizeSig.ExtractScalar(2); MATLAB fprintf %f\t
Edit1->Text = IntToStr(iNCh); // Edit1
Edit2->Text = IntToStr(iNLen); // Edit2 , .
, fprintf ,
, .
, fscanf ,
8 , .
mwArray .
void __fastcall TForm1::N3Click(TObject *Sender)
(Test_Sig.txt) 8 , Sig 8 . {
, if(SaveDialog1->Execute())
: Test_Sig.txt, Test_SigD.txt Test_SigD2.txt. {
mwArray fid;
. mwArray mode("wt");
( ) detrend mwArray file(SaveDialog1->FileName.c_str());
MATLAB. fid = fopen(file, mode);
mwArray TOut = ctranspose(DOut);
. fprintf(fid, "%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t\n", TOut);
Sig. max min fclose(fid);
. max min 8 }
}
. 28 vertcat.
(double) //-
Edit3 Edit4 . Project_71.exe:
Edit5.
Edit3 Edit4
.
//
mwArray X = ctranspose(Sig); //
mwArray Y = detrend(X,"constant"); //
mwArray MaxY = max(Y); // max
mwArray MinY = min(Y); // min
mwArray SigDt = ctranspose(Y); //
ready = true;
PaintBox1->Refresh();
}
,
PaintBox1:
void __fastcall TForm1::PaintBox1Paint(TObject *Sender)
{
if (ready) {
. 7.2.1. Form1 Project_72 int NN = ScrollBar1->Position;
// iNCh ,
// ,
// 20
: //
// int WinH = (PaintBox1->Height-20)/iNCh;
bool ready = false;
false , // iNCh ,
for (int NCh=1; NCh<=iNCh; NCh++){
. // mwArray
void __fastcall TForm1::N2Click(TObject *Sender) //
mwArray Tmp = MaxY(NCh);
double mMaxY = Tmp.ExtractScalar(1);
Tmp = MinY(NCh);
if(OpenDialog1->Execute()) double mMinY = Tmp.ExtractScalar(1);
{
// ... Project_71 ... //
PaintBox1->Canvas->TextOut(2, WinH*(NCh-1),
" "+IntToStr(NCh));
,
: //
mwArray SigTr = ctranspose(Sig); //
424 7. 7.3. / 425
//
// .
for(int i=1; i<PaintBox1->Width; i++) {
Tmp = SigDt(NCh, (NN+i));
y = floor(WinH*(mMaxY-Tmp.ExtractScalar(1))/(mMaxY-mMinY))+
WinH*(NCh-1);
PaintBox1->Canvas->LineTo(i,y);
}
//
PaintBox1->Canvas->MoveTo(0,0);
PaintBox1->Canvas->LineTo(0,PaintBox1->Height-5);
PaintBox1->Canvas->MoveTo(0,PaintBox1->Height-20);
. 7.2.2. Project_72
PaintBox1->Canvas->LineTo(PaintBox1->Width,
PaintBox1->Height-20);
7.3. ,
//
PaintBox1->Canvas->TextOut(2, PaintBox1->Height-18, Project_Wav.exe
IntToStr(NN)); Borland C++ Builder,
PaintBox1->Canvas->TextOut(PaintBox1->Width- ASCII,
PaintBox1->Canvas->TextWidth(IntToStr(NN+ .
PaintBox1->Width))-2, PaintBox1->Height-18,
IntToStr(NN+PaintBox1->Width));
(Project_72), ,
} , .
} (Project_Wav) Glava_7\Project_73\
} . , , Unit1.cpp.
, , Unit2.cpp .
,
. 7.3.1. ,
void __fastcall TForm1::Panel2Resize(TObject *Sender)
{
if ((iNLen - PaintBox1->Width)<0) , [10].
ScrollBar1->Max = 0; { sn }
else cA cD.
ScrollBar1->Max = iNLen - PaintBox1->Width;
}
.
/ / - [10]:
,
: (1)
void __fastcall TForm1::ScrollBar1Change(TObject *Sender)
{ }
PaintBox1->Refresh(); { h n} {g n
} . , { sn }
/ / N, cA cD ,
Project_72.exe: .
426 7. 7.3. / 427
( ) ,
[10]: ,
.
, (2)
{ hn } , { gn }
7.3.2.
.
cA, Unit2.cpp. .
, cD = 0, , 1. dwt.
s. , = dwt(F, S), S
cD, , cA = 0, , F. F LoD,
s. cA1 = dwt(LoD, S), F
HiD,
cD1 = dwt(HiD, S) .
. .
, 2, . 7.3.1. , . dwt
MATLAB C++:
conv ;
length ;
colon(2,2,Len_cX) .
, .
m MATLAB,
mwArray:
mwArray dwt(mwArray X, mwArray Y)
. 7.3.1. {
mwArray cX;
mwArray dwtX;//
,
. cX = conv(X,Y);
. . mwArray Len_cX = length(cX); //
. dwtX=cX(colon(2,2,Len_cX)); //
, . 7.3.2. return dwtX;
}
2. idwt.
cA1 cD1. (2)
,
idwt(cA, cD, LoR, HiR) = idwtA(cA, LoR) + idwtD(cD, HiR). idwtA
idwtD ,
. .
idwtA .
cA
. (2)
LoR. cA
LoR.
. 7.3.2. , S. idwtA:
428 7. 7.3. / 429
mwArray Spfft(mwArray X)
{
mwArray Len_X = length(X); //
mwArray Y, P;
Y = fft(X);
P = times(Y,conj(Y))/Len_X;
return P;
}
7.3.3.
:
1. . ,
.
Test_Sig.txt, Test_SigD.txt Test_SigD2.txt.
(
8). .
.
, .
( 3).
2. . , ,
db2. . 7.3.3.
( WF),
. ,
3. ( 4) , . . 7.3.3.
, . 2. . j
4. . . Wf.
430 7. 7.3. / 431
Edit8->Text = IntToStr(iSuppw); //
Edit9->Text = FloatToStrF(fFrw,ffGeneral,6,4); //
}
}
//
void __fastcall TForm1::WaveletsChange(TObject *Sender, TTreeNode *Node)
{
if(FileExists("WF\\"+Node->Text+".txt"))
{
mwArray WLen = mclGetInf(); //
mwArray u;
mwArray mod("rt");
String STR="WF\\"+Node->Text+".txt";
mwArray fil(STR.c_str());
//
u = fopen(fil, mod);
Wfilters = fscanf(u, "%g ", horzcat(5, WLen));
fclose(u);
Frw = Wfilters(5,1);
. 7.3.4. double fFrw = Frw.ExtractScalar(1);
432 7. 7.3. / 433
LF= length(LoD); //
Suppw = LF-1;
.
int iSuppw = Suppw.ExtractScalar(1);
int iLF = LF.ExtractScalar(1); .
Edit8->Text = IntToStr(iSuppw); //
Edit9->Text = FloatToStrF(fFrw,ffGeneral,6,4); //
ready4 = true;
}
}
. 7.3.5.
3. . ,
,
, . 7.3.2. , .
// -
// -
, ,
. void __fastcall TForm1::SpeedButton1Click(TObject *Sender)
, {
. , Sig if (ready3&&ready4) {
// -
NLen, , . TwCoef = cell(iJ,iNCh); //
, j = 1, K
TwCoef.cell(1,K) (1,K), TwComp = mwArray::UNDEFINED; //
2(NLen/2). cA1 TwComp = cell(iJ,iNCh);
, cD1: SpecComp = mwArray::UNDEFINED; //
TwCoef.cell(1,K)(1,colon()) = cA1; SpecComp = cell(iJ,iNCh);
TwCoef.cell(1,K)(2,colon()) = cD1;
(. 7.3.5) for(int K = 1; K <= iNCh; K++) //
{
(1,0) (1,1) . // -
, j = 2, K // -
TwCoef.cell(2,K) (2,K), mwArray cA1 = dwt(LoD, FragSig(K, colon()));
4(NLen/4), mwArray cD1 = dwt(HiD, FragSig(K, colon()));
(2,0), (2,1), (2,2) (2,3). : TwCoef.cell(1,K)(1,colon())= cA1;
mwArray coefAj = dwt(LoD, TwCoef.cell(1,K)(1,colon())); TwCoef.cell(1,K)(2,colon())= cD1;
TwCoef.cell(2,K)(1,colon())= coefAj;
// -
mwArray coefDj =dwt(HiD, TwCoef.cell(1,K)(1,colon())); mwArray compA1 = idwtA(cA1,LoR,FragLen);
TwCoef.cell(2,K)(2,colon())= coefDj; mwArray compD1 = idwtD(cD1,HiR,FragLen);
, j = 3, K TwComp.cell(1,K)(1,colon())= compA1;
, , TwComp.cell(1,K)(2,colon()) = compD1;
(3,0), (3,1), (3,2) (3,3). . . 7.3.5.
, J. TwCoef SpecComp.cell(1,K)(1,colon())= Spfft(compA1);
SpecComp.cell(1,K)(2,colon())= Spfft(compD1);
jK, TwCoef.cell(j,K)
j . LenCoef(1)= FragLen; //
, LenCoef(2)= length(cA1); // 1, iJ+1
.
//
, , . for(int j=2; j < iJ+1; j++) //
, TwComp. {
434 7. 7.3. / 435
// 1.
for (int i=2; i<=KMax; i++)
{ C++ MATLAB
//
x = R1.Left + (R1.Right-R1.Left)*(i-1)/KMax;
y = R1.Top + floor((R1.Bottom-R1.Top)*(mMaxY-
MATLAB C++. :
Tmp.ExtractScalar(i+ScrollBar2->Position))/(mMaxY-mMinY));
// ;
PaintBox4->Canvas->LineTo(x, y); MATLAB;
}
;
// MaxY MinY .
PaintBox4->Canvas->TextOut(R1.Left+2, R1.Top+2,
FloatToStr(floor(1000*mMaxY)/1000.0));
,
PaintBox4->Canvas->TextOut(R1.Left+2, R1.Bottom-15, .
FloatToStr(floor(1000*mMinY)/1000.0)); Help MATLAB MATLAB C++ Math Library Reference.
//
// SelLv SelCh MaxY MinY
Tmp = TwComp.cell(SelLv,SelCh)(SelKoef,colon());
.1.1.
TmpTr = ctranspose(Tmp); MATLAB C++
MaxY = max(TmpTr); // max-
: ,
mMaxY = MaxY.ExtractScalar(1); , ,
.
MinY = min(TmpTr); // min-
mMinY = MinY.ExtractScalar(1);
.
, + (), *
// ( ). , ,
x = R2.Left;
y = R2.Top + floor((R2.Bottom-R2.Top)*(mMaxY-
. ,
Tmp.ExtractScalar(1+ScrollBar2->Position))/(mMaxY-mMinY)); , mwArray
PaintBox4->Canvas->MoveTo(x, y); . , C++.
for (int i=2; i<=KMax; i++)
{
, 4 + 5 .
x = R2.Left + (R2.Right-R2.Left)*(i-1)/KMax; .
y = R2.Top + floor((R2.Bottom-R2.Top)*(mMaxY- . ,
Tmp.ExtractScalar(i+ScrollBar2->Position))/(mMaxY-mMinY));
PaintBox4->Canvas->LineTo(x, y);
,
} .
// MaxY MinY
PaintBox4->Canvas->TextOut(R2.Left+2, R2.Top+2,
FloatToStr(floor(1000*mMaxY)/1000.0));
.1.1. C++
PaintBox4->Canvas->TextOut(R2.Left+2, R2.Bottom-15, C++ ++
FloatToStr(floor(1000*mMinY)/1000.0));
+ plus()
} - minus(), unaryminus()
} * mtimes()
// / mrdivide()
^ mpower()
438 1. C++ .1.2. 439
MATLAB C++,
MATLAB C++ , .
.1.2.
MATLAB C++
.1.2. ++2 MATLAB C++ 400 ,
: MATLAB, ,
MATLAB ++ MATLAB, ,
\ mldivide() , MATLAB.
.\ ldivide() MATLAB.
.\ rdivide()
MATLAB.
.* times()
.^ power() MATLAB MATLAB C++
ctranspose() MATLAB. ,
. ( transpose() , .
. MATLAB C++ Math Lib
. rary Reference ( MATLAB 6). MATLAB:
. C++ M MATLAB. C++
. M
: C = (A op B), op MATLAB. , C++
, , C[i] == 1, ([i] op B [i]) , MATLAB eig();
C[i] == 0. . C++ MATLAB. , C++
MATLAB (*)
.1.3.
mtimes().
C++ ++
:
> gt()
< lt() computer ;
>= ge() eps ;
<= le() inf ;
== eq() nan ;
!= neq(), ne() pi 3.1415926535897...;
realmax ;
. : realmin .
, .
, .
C++ . 1.2.1. /
.1.4.
format ;
C++ ++ load ;
Math Library
save c .
(x)
(x, y)
| OR or_func() fclose ;
& AND And_func() fopen .
~ l NOT Not_func()
>>
<< feof ;
440 1. C++ .1.2. 441
realsqrt legendre .
();
sqrt . factor ;
gcd ;
abs , ; isprime True ;
angle , ; lcm ;
conj ; nchoosek n k;
cplxpair ; perms ;
imag , ; primes ;
isreal , ; rat ;
real ; rats .
unwrap
360. cart2pol ;
cart2sph ;
ceil , ; pol2cart ;
fix ; sph2cart .
floor ;
mod ( : mod(x,y) = x y*
floor(x/y));
1.2.6.
rem , rem(x,y) = x fix(x./y).*y;
round ; det ;
sign Signum. norm ;
normest 2 ( );
1.2.5. null
;
orth ;
rank ;
beta ; rcond LINPACK ;
betainc ; rref
betaln ; ;
cross ; subspace ;
ellipj ; trace .
ellipke ;
erf ; chol ;
erfc ; cond ;
erfcx ; condest 1;
erfinv ; inv ;
expint , exp(t)/t lscov ;
[x, +inf); lu ;
gamma ; nnls
gammainc ; ;
gammaln ; pinv ;
446 1. C++ .1.2. 447
qr .
del2 ;
condeig ; diff ;
eig ; gradient .
hess (Hessenberg) ;
poly ; corrcoef ;
polyeig ; cov ;
qz ; subspace .
schur ;
svd . conv ;
conv2 ;
expm ; deconv ;
funm ; filter ;
logm ; filter2 .
sqrtm .
fft ;
balance fft2 ;
; fftn ;
cdf2rdf fftshift ;
; ifft ;
planerot , , ifft2 ;
Ox; ifftn .
qrdelete QR;
qrinsert QR ;
freqspace ;
rsf2csf
lin2mu mu ;
.
mu2lin mu .
1.2.7. 1.2.8.
cumprod ;
griddata ;
cumsum ;
icubic ;
cumtrapz ;
interp1 (1D table);
max ;
interp1q ;
mean ;
interp2 ;
median ;
interpft , .
min ;
prod ;
sort ; ppval ;
sortrows ; spline .
std ;
sum ; inpolygon ;
trapz , . polyarea ;
448 1. C++ .1.2. 449
rectint .
odeget options, odeset;
conv ; odeset options
deconv ; .
mkpp ;
poly ; 1.2.10.
polyder ;
polyfit ,
; char_func ();
polyval ; double_func .
polyvalm ;
residue ; classname , ;
resi2 ; isa , .
roots ;
unmkpp . 1.2.11.
cat ;
1.2.9. ind2sub ( )
() ;
ipermute ;
ndims ;
fmin ; permute ;
fmins ; shiftdim ;.
foptions ; sub2ind
fzero ; .
optimget
;
optimset 1.2.12.
.
() blanks ;
dblquad ; char_func ();
quad (loworder method); deblank ;
quad8 (highorder method). double_func ;
str2mat .
ode23
, ode45; ischar True ;
ode45 ; isletter True ,
ode113 ;
; isspace True .
ode15s
; findstr ;
ode23s lower ;
, ode15s; strcat ;
450 1. C++ .1.2. 451
strcmp ; iscell ;
strcmpi , ; iscellstr , ;
strjust ; num2cell .
strmatch ;
strncmp n ; 1.2.14.
strncmpi n , ;
strrep ; fieldnames ;
strtok () ; getfield ;
strvcat ; isfield , ;
upper . isstruct , ;
rmfield ;
setfield ;
base2dec
; struct ;
bin2dec struct2cell .
;
dec2base 1.2.15.
;
dec2bin
spdiags , ;
;
speye ;
dec2hex
sprand
;
;
hex2dec
sprandn
;
;
hex2num
sprandsym .
.
find ;
int2str ;
full ;
mat2str ;
sparse ;
num2str ;
spconvert .
sprintf ;
sscanf ;
str2double ; issparse ;
str2num . nnz ;
nonzeros ;
nzmax
1.2.13. ;
cell c ; spalloc ;
cell2struct ; spfun ;
celldisp ; spones
cellfun ; .
cellhcat ;
cellstr ; cholinc ;
deal ; condest 1;
452 1. C++ .1.3. 453
eigs ; .
luinc LU ; mwOutputFunc
normest 2 ; mwGetPrintHandler(void);
svds . , mwSet
( ) PrintHandler (), ,
bicg ; .
bicgstab ;
cgs void mwSetPrintHandler(mwOutputFunc f);
; .
gmres ; () .
pcg ; .
qmr . void mwDisplayException(const mwException &ex);
, .
spaugment ,
; mwErrorFunc
spparms ; mwGetErrorMsgHandler(void);
symbfact . , mwSet
ErrorMsgHandler (), ,
1.2.16. .
mwExceptionMsgFunc
clock_func ; mwGetExceptionMsgHandler(void);
date ;
, mwSet
now .
ExceptionMsgHandler (),
, .
datenum ;
datestr ; void mwSetErrorMsgHandler(mwErrorFunc f);
datevec .
.
.
calendar ;
eomday ;
void mwSetExceptionMsgHandler(mwExceptionMsgFunc f)
weekday .
,
, .
etime ;
tic,toc / . .
.
.1.3. void mwSetLibraryAllocFcns(mwMemCallocFunc callocProc,
mwMemFreeFunc freeProc,
MATLAB CMath , mwMemReallocFunc reallocProc,
, , mwMemAllocFunc mallocproc,
. mwMemCompactFunc=0);
, . .
, MATLAB. MATLAB C++. .
454 1. C++ .1.4. 455
.1.5. .1.5.
() ()
mxGetElementSize , MATLAB C
mxGetEps eps mxIsStruct , mxArray .
mxGetField mxMalloc ,
MATLAB
mxGetFieldByNumber mxRealloc
. mxSetCell
mxGetFieldNameBy mxSetData
Number mxSetDimensions /
mxGetFieldNumber
mxGetImagData mxArray mxSetField
mxGetInf
mxGetIr ir mxSetFieldByNumber
mxGetJc jc
mxGetM, mxGetN (M) (N) mxSetImagData mxArray
mxGetName, mxArray bitcmp (Complement bits)
mxSetName mxSetIr i mxArray
mxGetNaN mxSetJc j mxArray
mxGetNumberOf mxSetLogical
Dimensions mxSetM, mxSetN (M) (N)
mxGetNumberOfElements mxSetNzmax
mxGetNumberOfFields mxArray mxSetPi, mxSetPr mxArray
mxGetNzmax ir, pr
( ) pi
mxGetPi, mxGetPr
mxArray
mxGetScalar
mxArray
mxGetString mxArray
mxIsChar
mxIsClass , mxArray
mxIsComplex ,
mxIsDouble , mxArray
mxIsEmpty , mxArray
mxIsFinite ,
mxIsInf ,
mxIsLogical , mxArray
mxIsNaN ,
mxIsNumeric , mxArray
mxIsSingle , mxArray
mxIsSparse , mxArray .
.2.1. 459
2.2.3. . str. .
. .
operator const char* () const.
. .
.
bool operator<(const mwString& str) const.
C++ :
true,
#include "mclcppclass.h"
mwString str("This is a string"); , .
const char* pstr = (const char*)str; C++ :
. . #include "mclcppclass.h"
mwString str("This is a string");
. .
mwString str2("This is another string");
. , bool ret = (str < str2); // ret should have a value of true.
.
. str. .
mwString& operator=(const mwString& str). mwString.
. .
C++ :
.
#include "mclcppclass.h"
mwString str("This is a string"); .
mwString new_str = str; // new_str contains a copy of the data in str. bool operator<=(const mwString& str) const.
. str. . true,
. mwString. .
. . C++ :
mwString& operator=(const char* str). mwString. #include "mclcppclass.h"
C++ : mwString str("This is a string");
mwString str2("This is another string");
#include "mclcppclass.h" bool ret = (str <= str2); // ret should have a value of true.
const char* pstr = "This is a string";
mwString str = pstr; // str contains a copy of the data in pstr. . str. .
. str. char . . .
. mwString. .
. , .
NULL , mwString. bool operator>(const mwString& str) const.
bool operator==(const mwString& str) const. true
mwStrings. .
C++ : bool operator>=(const mwString& str) const.
#include "mclcppclass.h" true,
mwString str("This is a string"); .
462 2. C++ .2.3. mwException 463
double im = 10.0; . .
mwArray a(re, im); // Creates a 1X1 complex array with value 5+10i
. mwArray mxUINT8_CLASS,
. .
re ; . .
im . 1n mxUINT8_CLASS,
. . .
. maArray::Deserialize().
. mxClassID ClassID() const. .
, . <type> C++ :
: mxDouble, mxSingle, mxInt8, mxUint8, mxInt16, mxUint16, mxInt32, #include "mclcppclass.h"
mxUint32, mxInt64, mxUint64. mwArray a(2, 2, mxDOUBLE_CLASS);
. mxClassID id = a.ClassID(); // mxDOUBLE_CLASS
. .
2.4.2. . mxClassID .
. . .
mwArray Clone() const. ,
mxClassID.
(deep copy)
int ElementSize() const. .
C++ :
C++ :
#include "mclcppclass.h"
mwArray a(2, 2, mxDOUBLE_CLASS); #include "mclcppclass.h"
mwArray b = a.Clone(); mwArray a(2, 2, mxDOUBLE_CLASS);
int size = a.ElementSize(); // sizeof(double)
. .
. .
. mwArray
. .
.
.
.
.
. .
mwArray SharedCopy() const. , int NumberOfElements() const. .
. C++ :
C++ : #include "mclcppclass.h"
mwArray a(2, 2, mxDOUBLE_CLASS);
#include "mclcppclass.h" int n = a.NumberOfElements(); // 4
mwArray a(2, 2, mxDOUBLE_CLASS);
mwArray b = a.SharedCopy(); . .
. . . .
. mwArray . .
. int NumberOfNonZeros() const.
.
. C++ :
. #include "mclcppclass.h"
mwArray a(2, 2, mxDOUBLE_CLASS);
mwArray Serialize() const.
int n = a.NumberOfNonZeros();// 4
mxUINT8_CLASS.
(Serialize the underlying array into a byte array). . .
C++ : . .
.
#include "mclcppclass.h"
mwArray a(2, 2, mxDOUBLE_CLASS); . , ,
mwArray s = a.Serialize(); NumberOfElements().
472 2. C++ .2.4. mwArray 473
C++ : C++ :
#include "mclcppclass.h" #include "mclcppclass.h"
double data[4] = {1.0, 2.0, 3.0, 4.0}; double data[4] = {1.0, 2.0, 3.0, 4.0};
double x; int index[2] = {1, 1};
mwArray a(2, 2, mxDOUBLE_CLASS); double x;
a.SetData(data, 4); mwArray a(2, 2, mxDOUBLE_CLASS);
x = a.Get(1,1); // x = 1.0 a.SetData(data, 4);
x = a.Get(2, 1, 2); // x = 3.0 x = a.GetA(1, index); // x = 1.0
x = a.Get(2, 2, 2); // x = 4.0 x = a.GetA(2, index); // x = 1.0
index[0] = 2;
. index[1] = 2;
num_indices ; x = a.Get(2, index); // x = 4.0
.... . .
num_indices. num_indices .
. mwArray, Index num_indices, .
. . MwArray,
. .
. , mwArray GetA(const char* name, int num_indices, const int* index).
. 1 <= index
<= NumberOfElements() () . . .
i 1 <= C++ :
index[i] <= GetDimensions().Get(1, i). #include "mclcppclass.h"
, mwException. const char** fields = {"a", "b", "c"};
mwArray Get(const char* name, int num_indices, ...). int index[2] = {1, 1};
mwArray a(1, 1, 3, fields);
. mwArray b = a.Get("a", 1, index);
, . mwArray b = a.Get("b", 2, index);
C++ : .
#include "mclcppclass.h" name , NULL, ;
const char** fields = {"a", "b", "c"};
mwArray a(1, 1, 3, fields); num_indices ;
mwArray b = a.Get("a", 1, 1); index num_indices, .
mwArray b = a.Get("b", 2, 1, 1);
. mwArray,
. .
Name , NULL, ; mwArray Real(). mwArray
num_indices ; .
... . C++ :
num_indices. #include "mclcppclass.h"
. mwArray, double rdata[4] = {1.0, 2.0, 3.0, 4.0};
double idata[4] = {10.0, 20.0, 30.0, 40.0};
. mwArray a(2, 2, mxDOUBLE_CLASS, mxCOMPLEX);
. a.Real().SetData(rdata, 4);
. a.Imag().SetData(idata, 4);
mxSTRUCT_CLASS, mwException. . .
. . mwArray.
, . .
mwArray GetA(int num_indices, const int* index). . mwArray
. . , .
478 2. C++ .2.4. mwArray 479
. 2.4.3.
buffer , ;
len . len , mwArray operator()(int i1, int i2, int i3, ..., ).
. .
. . . 1 32 .
. <numerictype> mxDOUBLE_CLASS, C++ :
mxSINGLE_CLASS, mxINT8_CLASS, mxUINT8_CLASS, mxINT16_CLASS, #include "mclcppclass.h"
double data[4] = {1.0, 2.0, 3.0, 4.0};
mxUINT16_CLASS, mxINT32_CLASS, mxUINT32_CLASS, mxINT64_CLASS, double x;
mxUINT64_CLASS. . mwArray a(2, 2, mxDOUBLE_CLASS);
, , a.SetData(data, 4);
. , x = a(1,1); // x = 1.0
x = a(1,2); // x = 3.0
mwException.
x = a(2,2); // x = 4.0
void SetLogicalData(mxLogical* buffer, int len).
mxLogical . . i1, i2, i3, ..., . .
C++ : . mwArray, , .
.
#include "mclcppclass.h"
mxLogical data[4] = {true, false, true, false}; . , ,
mxLogical data_copy[4] ; 1 ( ),
mwArray a(2, 2, mxLOGICAL_CLASS); NumberOfDimensions() ( ),
a.SetData(data, 4);
a.GetData(data_copy, 4); , .
1 <= index <= NumberOfElements()
.
buffer , ; . i
len . len , : 1 <= index[i] <= GetDimensions().Get(1, i).
. ,
mwException.
. .
mwArray operator()(const char* name, int i1, int i2, int i3, ..., ).
. .
, , .
mxLOGICAL_CLASS, .
.
, mwException.
1 32 .
void SetCharData(mxChar* buffer, int len).
C++ :
mxChar .
#include "mclcppclass.h"
C++ :
const char** fields = {"a", "b", "c"};
#include "mclcppclass.h" int index[2] = {1, 1};
mxChar data[6] = {'H', 'e' , 'l' , 'l' , 'o' , '\0'}; mwArray a(1, 1, 3, fields);
mxChar data_copy[6] ; mwArray b = a("a", 1, 1);
mwArray a(1, 6, mxCHAR_CLASS); mwArray b = a("b", 1, 1);
a.SetData(data, 6);
a.GetData(data_copy, 6); .
. name , NULL, ;
buffer , ; i1, i2, i3, ..., .
len . len , . mwArray, ,
. .
. . . ,
. . . ,
mxCHAR_CLASS, . mxSTRUCT_CLASS. mwException.
, mwException.
482 2. C++ .2.4. mwArray 483
, 30 , 14
Matlab, 114 , 19
, 17
, 15, 18
, 15, 18
C++ML
N, 280
, 57
, 18
, 281
. . VCL
, 286
, 22
C++ Builder, 13 , 283
SDI, 13 AnsiString, 58
DynamicArray, 66 , 279
Set, 62 CML , 120
M TApplication, 83 N, 216 feval, 294
MDI, 90 TBrush, 92 , 220 mcc
, 214 3, 333
TButton, 74
O , 15 4, 391
TCanvas, 93
Matlab
Object Inspector, 14 TCheckBox, 74
events, 15 , 137
Events, 18 TComboBox, 77
properties, 15 , 150
Properties, 15 TControl, 69
, 143
Object Tree View, 14 TEdit, 72
mxArray
TFont, 91
, 203
P TForm, 86 , 33 , 203
Project Manager, 16 TLabel, 71 , 40 , 183
Options, 16 TList, 65 , 39
TListBox, 76 , 49 C++ML, 296
R TMainMenu, 95 , 37 , 16
TMemo, 73 , 34 , 16
Rapid Application Development TMenuItem, 95 , 47 C++ML
Environment, 13
TOpenDialog, 98 , 45 cell(), 269
TPageControl, 82 , 42 EltCount(), 276
S TPaintBox, 94 inline, 30 field(), 286
SDI, 90 TPanel, 79 , 34 Size(), 276
TPen, 92 , 47 , 16
V TPopupMenu, 97 , 45
VCL, 58 TRadioButton, 75 , 45 (), 131
Visual Component Library. . VCL TSaveDialog, 98 , 50 , 132
TScrollBar, 78 this, 36
TStringGrid, 80 friends, 46
TStringList, 67 , 40
MCRInstaller, 402 TStrings, 68 mwArray, 250 , 128
TTabSheet, 82 , 19, 20
TTimer, 97
Matlab trycath, 168 , 18 , 99
492 493
. . , . . , . .
BORLAND C++ BUILDER
MATLAB /++
. .
dm@dmkpress.ru
. .
. .
. .
: www.dmkpress.ru