You are on page 1of 250

. . , . . , . .

Borland C++ Builder



MATLAB /++

, 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.4.1. .............................................. 58 2.6.1. ) .................................................................. 155


1.4.2. .............................................. 69 2.6.2. MATLAB ..................................... 160
1.4.3. ................................................ 83 2.6.3.
TForm ............................................................................ 86 ....................................................... 163
1.4.4. ................................................. 98 2.6.4. .......................... 167
1.5. C++ Builder .......... 99 2.6.5. ......................................... 168
2.6.6. ) ...... 169
2. MATLAB
3. MATLAB
2.1. MATLAB..................... 109
2.1.1 MATLAB ..................... 110 C
2.1.2. MATLAB ... 111 3.1. ........................................................................... 171
2.1.3. MATLAB ............ 117 3.1.1. MATLAB ........ 172
2.1.4. MATLAB .................................................. 117 3.1.2. ....................... 174
2.2. MATLAB .................................................. 120 3.1.3.
2.2.1. MATLAB ................................. 120 MATLAB C .......................................................... 174
2.2.2. ...................................................... 122 3.1.4. MATLAB C ................................ 175
2.2.3. ........................................... 125 3.1.5. ..................... 176
2.2.4. ........................ 128 3.1.6. ...................... 178
2.2.5. ) ..................................................................... 131 3.2. mxArray .............................................. 182
2.2.6. ............................. 133 3.2.1. MATLAB .................. 182
2.2.7. ........ 136 3.2.2. ...................................................... 183
2.3. ............................................................ 137 3.2.3. ................................................ 188
2.3.1. ........................................ 137 3.2.4. ..................................................... 191
2.3.2. .......................................................... 138 3.2.5. ............................................................ 193
2.3.3. ........................................................... 139 3.2.6. MATLAB ...................................................... 196
2.3.4. .............................................. 139 3.2.7.
2.3.5. .............. 141 ......................................................................... 198
2.3.6. .............. 142 3.3. ............................................ 202
2.3.7. ............................. 143 3.3.1.
2.4. ................................................................... 143 ...................................................................... 202
2.4.1. ........................................... 144 3.3.2.
2.4.2. .......................................... 146 ............................................................ 205
2.4.3. .......................................... 147 3.4. ...................................................... 210
2.4.4. , ...................... 149 3.4.1. .................................................................... 211
2.4.5. ..................................... 149 3.4.2. .................................................. 212
2.5. .............................................................. 150 3.4.3. ................................. 214
2.5.1. .................................................. 150 3.4.4. ......................................... 220
2.5.2. ........................... 151 3.4.5. .................................... 223
2.4.3. ................................. 154 3.5. .............................................. 225
2.6. MATLAB .................................. 154 3.5.1. MATLAB .................................. 226
6 7

3.5.2. .................. 231 4.5.2. / .......... 301


3.5.3. ............. 238 4.5.3. MAT) ......................... 305
3.6. ................................................... 239 4.6. mwArray ................................................ 307
3.7. ....................... 241 4.6.1. .............................................................. 308
4.6.2. ................................................................. 309
4. MATLAB 4.6.3. .................................................................. 311
C++ 4.6.4. .......................................................... 312
4.1. ........................................................................... 244 4.6.5. mwArray ................................... 312
4.1.1. ..................... 245 5. MATLAB 3.0
4.1.2. ....................... 246
4.1.3. 5.1. MATLAB ........................................ 315
MATLAB C++ ...................................................... 248 5.1.1. ..................................... 316
5.1.2. mcc............................... 318
4.1.4. MATLAB C++ ............................ 249
5.1.3. MATLAB .................. 320
4.1.5.
5.1.4. ........................................ 323
MATLAB C++ .................................................... 250
5.1.5. ) ..................................... 324
4.1.6. ++) ..................... 252
5.2. mbuild ..................................................................... 325
4.1.7. ...................... 255
5.3. mcc .................................................... 328
4.2. mwArray ............................................. 257
5.3.1. ....................... 328
4.2.1. ...................................................... 258
5.3.2. mcc .................................................................. 329
4.2.2. ................................................ 263
5.3.3. mcc ................... 332
4.2.3. ..................................................... 265 5.3.4. .................................................. 335
4.2.4. ............................................................ 267 5.3.5. .... 337
4.2.5. ................................................................... 270 5.3.6. mbuild/mex ....................................................... 339
4.2.6. 5.4. ................ 340
......................................................................... 271 5.4.1. ............................. 341
4.3. ...................................................... 278 5.4.2. ......................... 346
4.3.1. ................................. 279 5.4.3. ................ 352
4.3.2. ..................................... 283 5.5. .................................... 353
4.3.3. MATLAB ................... 286 5.5.1. ......................................... 353
4.3.4. .................................. 288 5.5.2. ............................... 356
4.4. ............................................... 289 5.5.3. .......................... 360
4.4.1. C++ ...................... 289 5.5.4. ........................... 362
4.4.2. 5.5.5. ......................... 364
................................................................ 293 5.6. ................................................. 367
4.4.3. .................. 294
4.4.4. .............. 296 6. MATLAB 4
4.4.5. 6.1. ........................................................................... 372
C........................................................................ 297 6.1.1. ....................... 372
4.5. ...................................................... 299 6.1.2. MATLAB 4
4.5.1. ) ........... 299 .................................................... 375
8 9

6.1.3. MATLAB ........................ 378 1.2.3. ..... 442


6.2. .......................................................... 379 1.2.4. ................... 443
6.2.1. MATLAB .................... 379 1.2.5. ........ 444
6.2.2. , mcc ........................................... 381 1.2.6. ...................................... 445
6.2.3. mbuild ........................................................... 382 1.2.7. .................... 446
6.3. mcc .................................................. 384 1.2.8. ................... 447
6.3.1. mcc .................................................................. 385 1.2.9.
6.3.2. ..................................... 392 ............................................ 448
6.3.3. ................................. 394 1.2.10. ............................................................. 449
6.3.4. ......................... 394 1.2.11. .............................. 449
6.3.5. ) ............................................................ 395 1.2.12. .......................................... 449
6.4. ................................................... 396 1.2.13. ............................................ 450
6.4.1. m) ............................ 396 1.2.14. ...................................................... 451
6.4.2. ) C C++ .................. 398 1.2.15. .................................. 451
6.4.3. ........................... 400 1.2.16. ............................................................ 452
6.4.4. ............................................... 402 .1.3. ....................................................... 452
6.4.5. ) ............. 402 .1.4. .......................................... 455
6.5. ........................................................................ 404
6.5.1. C ................. 405 2. C++
6.5.2. C++) ............. 409 4 MATLAB
6.5.3. , m) .............................. 412 .2.1. ................................................... 458
6.5.4. varargin .2.2. mwString ............................................................... 458
varargout m) ................................... 413 2.2.1. .............................................................. 459
7. 2.2.2. ....................................................................... 460
2.2.3. .................................................................. 460
Borland ++ Builder
++ MATLAB .2.3. mwException ......................................................... 462
2.3.1. .............................................................. 462
7.1. , ................................... 415 2.3.2. ....................................................................... 464
7.2. mwArray .............................. 421 2.3.3. .................................................................. 464
7.3. ) ............................. 425 .2.4. mwArray ................................................................ 465
7.3.1. ) .................. 425 2.4.1. .............................................................. 466
7.3.2. ................................... 426 2.4.2. ....................................................................... 470
7.3.3. ..................................... 428 2.4.3. .................................................................. 481
2.4.4. ................................................... 482
1.
C++ MATLAB # .................................................. 485
.1.1. ...................................................................... 437 ................................................................................ 489
.1.2. MATLAB C++ ....... 439
1.2.1. / .................................. 439 .......................................................... 490
1.2.2. ............................ 440
11

MATLAB Borland C++ Builder Windows


, 
.
.
Borland
++ Builder 6. , 
, MATLAB, /++. 
 , , Borland ++
Borland C++ Builder Builder. , Borland ++ Builder 
++ MATLAB.  , . 
Borland C++ Builder MATLAB, ++.
MATLAB /++ MATLAB MATLAB.
( ). Borland , ,
C++ Builder, MATLAB. MATLAB. , 
MATLAB /++ ,
Borland C++ Builder , , MATLAB.
MATLAB 3 C. 
/++ Borland C++ Builder. 400 ,
,
C. ,
( 
MATLAB, 
),
.
++, 
, 
++, MATLAB,
( 
++ Borland C++ Builder
).
MATLAB
4 MATLAB C++.
MATLAB .
MATLAB , , 
, , .
MATLAB, (dll) . MATLAB  C++
: MATLAB C Math Library, MATLAB C++ , MATLAB. C++
Math Library MATLAB Compiler /++ MATLAB mwArray MATLAB.
MATLAB.  MATLAB Compiler
MATLAB. 3 ( MATLAB 6.). MATLAB m MATLAB 
++ 20  MEX, C C++ , ,
. ++,  , C S Simulink,
, , Excel COM. 
. ,  MATLAB 6 (
, . MATLAB Compiler).
MATLAB MATLAB C/C++ Math Library MATLAB Compiler 6 4 ( MATLAB R14)
( 400), . 
/++.  . , 4
++  MATLAB ( MATLAB R14 
MATLAB. , ). . MATLAB
. MATLAB.
12
7 Windows
Borland ++ Builder
MATLAB ++. , 
.
.
MATLAB ++. 2 1.
C++ MATLAB 
4.  , Borland C++ Builder
.
MathWorks Borland C++ Builder
MathWorks , MATLAB. (Rapid Application Development Environment), 
MathWorks  C++
MATLAB (Visual Component Library), Borland Delphi.
. , , , 
. : ++,
C++ Builder, , 
, 
.

1.1.
C++ Builder (SDI),
( ) , 
( )
( ). , C++

.1.1.1. C++ Builder


14 1. 1.1. 15

Builder (Object Tree View), . 


(Object Inspector), (, Form1) . 
(, Unit1.cpp). ,
, 
1.1.1. .
. .
, 16  , ,
( , . 
). : , , 
. ,
, , , , 
C++ Builder 
, , . . 
. (
,
) .
.

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

IEEE. float double 32 64  1.3.5.


. long double,
80 , , :
long double test_case. * ;
*const ;
1.3.1. & & ;

[] ;
() () .
unsigned char 8 0 <= X <= 255
1.3.2.
char 8 -128 <= X <= 127
ASCII
short int 16 -32768 <= X
<= 32767 type name; type int count;
unsigned int 32 0 <= X type name[]; type int count[];
<= 4294967295 type name[3]; int count[3];
int 32 -2147483648 <= type (name[0], name[1] name[2];)
X <= 2147483647 type *name; type int *count;
int 32 -2147483648 <= type *name[]; int *count[];
X <= 2147483647 type
unsigned long 32 0 <= X type *(name[]); int *(count[]);
<= 4294967295 type (*name)[]; type int (*count) [];
enum 32 -2147483648 <= type &name; type ( C++) int &count;
X <= 2147483647 type name(); type int count();
long 32 -2147483648 <= , type *name(); , type int *count();
X <= 2147483647 type *(name()); int *(count());
float 32 1.18 10^-38 < |X| 7 type (*name)(); , int (*count) ();
< 3.40 10^38 type
double 64 2.23 10^-308 < |X| 15
< 1.79 10^308
long double 80 3.37 10^-4932 < ,
|X| < 1.18 10^4932 18 ().
:
1.3.4. char v[10]; // 10
const. ,  , v
, , ,  : v[0] ... v[9].
const . , :
const float pi = 3.14; int a[100], s = 0;
const char plus = '+'; ...
, , for (int i=0; i<100; i++)
. , , , , s = s + a[i];
, , , 
, , . , :
. int m[10] = {1, 23, 11, 54, 21, 222, 12, 345, 67, 11};
24 1. 1.3. ++ 25

),
. . , 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; //

address jd; struct link {


jd.name = " "; link* pre;
jd.number = 12; link* suc;
list* member_of;
: };
address jd = {" ", 61, ". ", "",
{'R','U'}, 7974}; struct list {
link* head;
,  }
jd.country RU, C++ list link .
\0, RU , ,
jd.country.
,  C++ Builder 
. : , . , , 
, 
address current;
, . ,
address set_current(address next){ C++ Builder Visual Component Library (
address prev = current; ), Bor
current = next; land Delphi, Object Pascal.
return prev;
}
Object Pascal , ( )
. , , :
, (== !=),  char *p; //
. . char *const q; //
,
. , ,  :
,  char c, d;
( : ...
26 1. 1.3. ++ 27

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 tbl; ostream ostream::operator<<(char* p) {


}; while (*p)
buf.sputc(*p++);
name,
table::~table(). return *this;
: }
#include << ostream.
name *table::look(char *p, int ins){ , ,
int ii = 0;
:
char *pp = p;
while (*pp) ii = ii<<1 ^ *pp++; &s1 == &my_out
, 
if (ii < 0) ii = -ii;
ii %= size;
, (
for (name *n=tbl[ii]; n; n=n->next) ):
if (strcmp(p, n->string) == 0) return n; ostream& operator<<(ostream& s, complex z) {
return s << "(" << z.real << "," << z.imag << ")";
if (ins == 0) error(" "); }
, ,
name *nn = new name;
nn->string = new char[strlen(p)+1]; s, 
strcpy(nn->string,p); , . ,
nn->value = 1; , ,
nn->next = tbl[ii]; , .
tbl[ii] = nn;

return nn; , 
}; .
, class istream {
//...
. int state;
. , .  public:
. istream& operator>>(char&);
, , , istream& operator>>(char*);
istream& operator>>(int&);
. istream& operator>>(long&);
, MS Windows //...
, , };
, , long int ,
(DLL). . , int long 
, , , .
int long
ostream,  , , , 
<< , .
44 1. 1.3. ++ 45

, 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 triangle: public shape { class red : public color {


point a, b, c; public:
public: ~red() { //
triangle (int x1, int y1, int x2, int y2, int x3, int y3) : std::cout << " red \n";
((x1+x2+x3)/3, (y1+y2+y3)/3) { }
50 1. 1.3. ++ 51

}; :
;
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"

double msqrt2 (double x){


1
( ),  return 2*sqrt(x);
, MSWindows  };
. // math1.cpp
54 1. 1.3. ++ 55

: , , 
#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

IsEmpty AnsiString s="


AnsiString s1=s.Trim();
";

bool IsEmpty(); : ""


IsEmpty true, AnsiString ,  TrimLeft
false. AnsiString TrimLeft();
LastDelimiter TrimLeft ,
.
int LastDelimiter(const AnsiString& delimiters);
,  TrimRight
delimiters. AnsiString TrimRight();
AnsiString s = "c:\\filename.ext"; TrimRight , 
s.LastDelimiter("\\.:" ); .
: s = 12.
LowerCase
Length AnsiString LowerCase();
int Length(); LowerCase , 
. . .
AnsiString s = "";
int i = s.Length(); UpperCase
: i = 6. AnsiString UpperCase();

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

AnsiString s1 = ""; Set <char, 'A', 'C'> s1;


AnsiString s2 = "2"; Set <char, 'X', 'Z'> s2;
if (s1==s2) {...};
 ( 
. ) char A C X Z
. .
: 
typedef, :
1.4.3. typedef Set <char, 'A','Z'> UPPERCASESet;

bool StrToBool(AnsiString S) :
Currency StrToCurr(AnsiString S) Currency UPPERCASESet s1, s2;
TDateTime StrToDate(AnsiString S) TDateTime s1 << 'A' << 'B' << 'C'; //
Extended StrToFloat(AnsiString S) s2 << 'X' << 'Y' << 'Z'; //

(. 1.4.4):
int StrToInt(AnsiString S)
AnsiString BoolToStr(bool B, bool .
UseBoolStrs = false) true 1, 1.4.4.
false 0. UseBoolStrs = true, true
TRUE, false FALSE Clear()
AnsiString CurrToStr(Currency Value) , Contains(el) true, el
Empty() true,
) ,
AnsiString DateToStr(TDateTime D)
!=
AnsiString FloatToStr(Extended Value) , * ,

*=
AnsiString IntToStr(int Value)
+=

<< ()
<< ( )
C++ Builder  )=
. , ,
+ ,
. 
Delphi. Set = ()
sysset.h. : ==
Set <, min , max > >> ( )
>> ()
:
( int, char enum);
VCL 
min ,
:
( 0);
if ( MessageDlg(" " + FileName +
max , " . ?",
( 255). mtConfirmation, TMsgDlgButtons() << mbYes << mbNo, 0) == mrYes) {
// "Yes"
Set , . ...
: }
64 1. 1.4. VCL 65

, .
 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;

for (int i=arrayOfInt.Low; i<=arrayOfInt.High; i++)


1.4.5. TList
total += arrayOfInt[i];
return total;
} Count TList
Items[Index] .
, Low 0, High
Index , 0
Length-1, : , 1 , . .
for (int i=0; i<arrayOfInt.Length; i++)
,  :
, TList *List = new TList();
. , for (i = 0; i < List->Count; i++) { List->Add(new TItem()); ... };
66 1. 1.4. VCL 67

TList // Canvas Paintbox.


int Y = 10; // Canvas
1.4.6. TList for (int i = 0; i < MyList->Count; i++){
AStruct = (PAList) MyList->Items[i];

PaintBox1->Canvas->TextOut(10, Y, IntToStr(AStruct->I));
int Add(void*) TList Y += 30; // Y
PaintBox1->Canvas->TextOut(10, Y, AStruct->C);
Clear() Y += 30; // Y
Delete(int Index) , Index }
Exchange(int Index1, int Index2) Index1
// ,
Index2 for (int i = 0; i < MyList->Count; i++){
Extract(void * Item) Item AStruct = (PAList) MyList->Items[i];
Void * First(void) TList delete AStruct;
int IndexOf(void * Item) Item }
Void Insert(int Index, void * Item) Item Index. delete MyList;
void * Last(void) TList }
Pack() NULL ,

TStringList
int Remove(void * Item) Item , TList
AnsiString, . ,
Sort(TListSortCompare Compare) , int Compare(void * Item1, TStrings.
void * Item2) ,
: > 0 (), Item1 1.4.7. TStringList
Item2; 0 , Item1 Item2;
<0 (), Item1 Item2
int Count
.  AnsiString Strings[int Index] , Index = 0
PaintBox:
//
1.4.8. TStringList
typedef struct AList{
int I;
char C;
Add(AnsiString Str) Str
} TAList; Clear() ,
Delete(int Index) Index
typedef TAList* PAList; Exchange(int Index1, int Index2) Index1 Idex2
bool Find(const AnsiString S, int &Index) S , Index
void __fastcall TForm1::Button1Click(TObject *Sender){ true
PAList AStruct;
TList *MyList = new TList;
int IndexOf(AnsiString S) S
// TList
Insert (int Index, const AnsiString S) S Index
AStruct = new TAList; Sort()
AStruct->I = 100;
AStruct->C = 'Z'; void __fastcall TForm1::Button1Click(TObject *Sender){
MyList->Add(AStruct); int Index;
TStringList* MyList = new TStringList();
AStruct = new TAList;
AStruct->I = 100; try {
AStruct->C = 'X'; MyList->Add("Animals");
MyList->Add(AStruct); MyList->Add("Flowers");
MyList->Add("Ocean");
// , // Find
68 1. 1.4. VCL 69

MyList->Sort(); 1.4.10. TStrings ()


if (MyList->Find("Flowers", Index)){
ListBox1->Items->AddStrings(MyList); LoadFromFile(AnsiString FName) FName
Label1->Caption = "Flowers has an index value of " + Operator []
AnsiString(Index);
Strings.
}
__finally { AnsiString operator[](int Index)
delete MyList; { return Strings[Index]; }
} SaveToFile(AnsiString FName) FName
}
:
TStrings
TStrings *StringList = new TStringList();
, try{
TStringList, .  StringList->Add(" TStrings");
,  StringList->Add("TStrings *StringList = new TStringList();");
StringList->Add(" , TStringList");
. StringList->Add(" TStrings");

1.4.9. TStrings Memo1->Lines->Assign(StringList);


}
__finally{
delete StringList;
int Count }
AnsiString Strings[int Index] , Index = 0
AnsiString Text
, 1.4.2.
TControl

AnsiString Values[AnsiString Name] TStrings : ,
DisplayGrid=1 TControl, , 
SnapToGrid=1 , , . .
GridSizeX=8
GridSizeY=8 1.4.11. TControl

, :
AnsiString a = MyList)>Values[GridSizeY]; TAlign Align
, :
alNone , )
1.4.10. TStrings ;
alTop
, ;
Append(AnsiString S) .
alBottom ;
Add,
alLeft , ;
int Add(AnsiString Str) Str ) alRight ;
alClient ;
Clear() , alCustom CustomAlignInsertBefore
Delete(int Index) Index stomAlignPosition
Exchange(int Index1, int Index2) Index1 Idex2 TAnchors Anchors )
int IndexOf(AnsiString S) S . Align,
Insert (int Index, const AnsiString S) S Index
Assign(TPersistent Obj) enum TAnchorKind { akLeft, akTop, akRight, akBottom };
Obj typedef Set<TAnchorKind, akLeft, akBottom> TAnchors;
70 1. 1.4. VCL 71

1.4.11. TControl 1.4.13. TControl ()


()
Sender ,
AnsiString Caption (,
TLabel TButton) OnDblClick(TObject *Sender)
TColor Color
bool ParentColor true, OnMouseDown(TObject*
, Sender, TMouseButton . Button )
TFont* Font Button, TShiftState Shift, , Shift
bool ParentFont true, , ) int X, int Y) , X Y
, ,
Font
OnMouseMove(TObject* . Shift
int Left (
Sender, TShiftState Shift, ,
)
int X, int Y) X Y
int Top (
) OnMouseUp(TObject* .
int Width ( ) Sender, TMouseButton
int Height ( ) Button, TShiftState Shift, OnMouseDown
bool Enabled , int X, int Y)
,
bool Visible
AnsiString Hint TLabel
bool ShowHint , . , , 
bool ParentShowHint ShowHint TEdit.

TLabel 
( ).
1.4.12. TControl

1.4.14. e ,
Hide() TControl
Show() ,
Refresh()
int Left (
,  )
, int Top (
. ,  )
, C++ Builder int Width ( )
int Height ( )
. 
TColor Color
, TControl. ,
bool WordWrap (
Width Height)
(TObject *Sender), . bool Transparent
(true , ; false
1.4.13. TControl
)
bool AutoSize , Width
OnClick(TObject *Sender) , Height , . false,
( ) ( ) ,
( ). Width Height
72 1. 1.4. VCL 73

, // , 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;
...
. . };

1.4.16. , TEdit TControl ...



// TEdit :
AnsiString Text / TEdit void __fastcall TForm1::Edit1Change(TObject *Sender)
bool CanUndo , , {
try { //
bool ReadOnly true, AnyNumber = StrToInt(Edit1->Text);
IsNumberOk = true; //
bool Modified True, };
catch ( ... ) {//
IsNumberOk = false;
1.4.17. TEdit };
}
OnChange(TObject *Sender) , ,
( ) , , :
OnEnter(TObject *Sender) , void __fastcall TForm1::Button1Click(TObject *Sender)
( ) {
OnExit(TObject *Sender) , <Tab> if (IsNumberOk) {- };
OnKeyDown(TObject* , ) else { };
Sender, Word &Key, , . Key , Shift }
TShiftState Shift)
, ,
)
OnKeyPress(TObject* . Key .
Sender, char &Key) 
OnKeyUp(TObject* Sender, OnKeyDown, O.
Word &Key, TShiftState Shift)
TMemo
:  , TEdit, 
, : , , .
74 1. 1.4. VCL 75

1.4.18. TMemo 1.4.20. TCheckBox



AnsiString Lines[int Index] . ) bool AllowGrayed ,
TStrings bool Checked , AllowGrayed = false,
TStrings TCheckBox
[] ( ),
TScrollStyle ScrollBars
TCheckBoxState State AllowGrayed = true,
TMemo.Enum TScrollStyle { ssNone, ssHorizontal, .
ssVertical, ssBoth } enum TCheckBoxState {cbUnchecked, cbChecked, cbGrayed}
bool WantReturns
TButton, TCheckBox
bool WantTabs OnClick(TObject *Sender). :
void __fastcall TForm1::CheckBox1Click(TObject *Sender){
bool WordWrap PageControl1->MultiLine = CheckBox1->Checked;
}

void __fastcall TForm1::FormCreate(TObject *Sender){


TMemo TEdit.
Checkbox1->Caption = "Stack Tabs?";
For (int i = 0; i < 20; i++){
TButton TTabSheet *pPage = new TTabSheet(PageControl1);
TButton  pPage->PageControl = PageControl1;
OnClick(TObject *Sender). , pPage->Caption = AnsiString("Page") + IntToStr(i);
}
TButton , }
,
, TRadioButton
( , TForm). () TRadioButton
.
1.4.19. TButton TCheckBox, TRadioButton
()
bool Cancel , OnClick TRadioButton. . 
Esc  ,
bool Default , OnClick , ,
Enter .
TModalResult ModalResult ,
1.4.21. TRadioButton

TCheckBox bool Checked . True,
TCheckBox () ,  .

, / // 
AnsiString Caption
( ). 
Checked State, , TButton, 
. OnClick(TObject *Sender).
TCheckBox,  , 
. TRadioGroup.
76 1. 1.4. VCL 77

TListBox for (int i = 0; i < FileListBox1->Items->Count; i++){


if (FileListBox1->Selected[i]){
TListBox () if (!FileExists(FileListBox1->Items->Strings[i])){
.  MessageBeep(0);
, . . ...
}
, , }
 }
. OnClick(TObject
*Sender).
1.4.22. TListBox

TComboBox
TComboBox ( )
bool AutoComplete , ItemIndex
, , , TListBox,
TEdit. , 
int Columns , .. , . TComboBox
, 
, , .

int Count , 1.4.24. TComboBox
bool ExtendedSelect MultiSelect = true,
, <Ctrl>
<Shift> bool AutoComplete , ItemIndex
bool IntegralHeight ,
int ItemIndex MultiSelect = false,
AutoDropDown ,
TStrings* Items
bool MultiSelect TEditCharCase CharCase ,
int SelCount , ) .
. MultiSelect = false, SelCount = 1 enum TEditCharCase {ecNormal, ecUpperCase, ecLowerCase}
bool Selected[int Index] , . AnsiString SelText ,
MultiSelect bool Sorted
bool Sorted true, TComboBoxStyle Style TComboBox.
:
csDropDown ,
;
1.4.23. TListBox
csSimple ;
csDropDownList ,
AddItem(AnsiString Item, . Item ,
TObject* AObject) AObject int ItemIndex
Clear() . TStrings* Items
ListBox1)>Clear();
ListBox1)>Items)>Clear(); 1.4.25. TComboBox
ClearSelection()
CopySelection
(TCustomListControl * TListBox TComboBox AddItem(AnsiString Item, . Item ,
Destination) TObject* AObject) AObject
DeleteSelected() Clear()
SelectAll() ClearSelection()
78 1. 1.4. VCL 79

1.4.25. TComboBox () 1.4.27. TScrollBar ()



CopySelection int Position
(TCustomListControl * TListBox TComboBox Word SmallChange .
Destination) 1
DeleteSelected()
SelectAll() 1.4.28. TScrollBar

1.4.26. TComboBox
OnChange(TObjectTObject* Sender)
OnScroll(TObject *Sender, TScrollCode
OnChange(TObjectTObject* Sender) , ScrollCode, int &ScrollPos) .
enum TScrollCode {scLineUp, scLineDown,
scPageUp, scPageDown, scPosition, scTrack,
OnCloseUp(TObjectTObject* Sender) scTop, scBottom, scEndScroll}
OnDropDown(TObjectTObject* Sender)
OnSelect(TObjectTObject* Sender) void __fastcall TForm1::FormCreate(TObject *Sender){
// PageControl1
void __fastcall TForm1::FormCreate(TObject *Sender){ PageControl1->TabWidth = PageControl1->ClientWidth/4 - 1;
for (int i = 0; i < PageControl1->PageCount; i++){ PageControl1->ActivePage = PageControl1->Pages[0];
ComboBox1->Items->AddObject(PageControl1->Pages[i]->Name,
PageControl1->Pages[i]); // ScrollBar1
ComboBox1->ItemIndex = 0; ScrollBar1->Max = PageControl1->PageCount - 1;
} ScrollBar1->Min = 0;
} ScrollBar1->SmallChange = 1;
ScrollBar1->LargeChange = PageControl1->ClientWidth /
void __fastcall TForm1::ComboBox1Change(TObject *Sender){
PageControl1->TabWidth;
TComboBox *pCB = dynamic_cast<TComboBox *>(Sender);
}
if (pCB)
PageControl1->ActivePage =
(TTabSheet *)(pCB->Items->Objects[pCB->ItemIndex]); void __fastcall TForm1::PageControl1Change(TObject *Sender){
} ScrollBar1->Position =
((TPageControl *)Sender)->ActivePage->PageIndex;
TScrollBar }
TScrollBar  void __fastcall TForm1::ScrollBar1Scroll(TObject *Sender,
. TScrollCode ScrollCode, int &ScrollPos){
, PageControl1->ActivePage = PageControl1->Pages[ScrollPos];
. }

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.29. TPanel 1.4.30. TStringGrid


()
TAlignment Alignment . :
taCenter ; TStrings* Cols[int Index] Index
taLeftJustify ; TStrings* Rows[int Index] Index
taRightJustify int Col ,
TBevelCut BevelInner int Row ,
. : int ColCount
bvNone ; int RowCount
bvLowered ; int ColWidths[int Index] Index
bvRaised int DefaultColWidth ,
TBevelCut BevelOuter
int BevelWidth int RowHeights[int Index] Index

bool DefaultDrawing /
TBorderStyle BorderStyle . :
, , ,
bsNone ;
, ..
bsSingle
int DefaultRowHeight
int BorderWidth

bool FullRepaint /
bool EditorMode / .
, Options
goAlwayseShowEditor
OnResize goEditing
(TObjectTObject* Sender), TColor FixedColor
 int FixedCols
. int FixedRows
TGridOptions Options ,
TStringGrid .
TStringGrid  C++Builder
, . TScrollStyle ScrollBars .
,  enum TScrollStyle {ssNone, ssHorizontal, ssVertical, ssBoth}
. ,
. , 1.4.31. TStringGrid
,
. OnColumnMoved(TObject* )
. Sender, long FromIndex, .
,  long ToIndex) FromIndex ;
. ToIndex)
.  OnGetEditText(TObject*
, . Sender, long ACol, long Value
. ARow, AnsiString &Value) (ACol, ARow)
. OnRowMoved(TObject* )
Sender, long FromIndex, .
long ToIndex) FromIndex ;
1.4.30. TStringGrid ToIndex)
OnSelectCell(TObject* , (ACol, ARow).
AnsiString Cells[int ACol][intARow] Sender, long ACol, long CanSelect false,
(ACol, ARow) ARow, bool &CanSelect)
82 1. 1.4. VCL 83

1.4.31. TStringGrid () 1.4.33. TPageControl ()



OnSetEditText(TObject* Value OnChange(TObject* Sender)
Sender, long ACol, long (ACol, ARow) OnDrawTab(TCustomTabControl* Control,
ARow, const AnsiString Value) Control, int TabIndex, const TabIndex )
TRect &Rect, bool Active) Rect. Active
void __fastcall TForm1::Button1Click(TObject *Sender){
int I, J, K;
K = 0;
for (I = 0; I < StringGrid1->ColCount; I++) 1.4.3.
for (J = 0; J < StringGrid1->RowCount; J++)
StringGrid1->Cells[I][J] = IntToStr(++K); TApplication
} , TApplication.
TPageControl
. TApplication 
 .  , 
. .
 . , 
Project\Options, 1.4.34. TApplication
. , 
, . , bool Active true,
,  .
New Page. TTabSheet true,
TPageControl, TPanel. Active true.
, ,
, TPageControl, (
), TTabSheet. TCanvas
,  AnsiString ExeName ,
. )
MultiLine false.
,
)
1.4.32. TPageControl .
ExtractFileDir ExtractFilePath.
TTabSheet* ActivePage () ExtractFileName. ExtractFileExt
, ExtractFileDrive
int ActivePageIndex ,
int PageCount AnsiString Hint C , )
TTabSheet* Pages[int Index] , ,
. )
, ,
1.4.33. TPageControl
bool ShowHint false

OnChanging(TObject* Sender, ,
bool &AllowChange) . TColor HintColor .
AllowChange false, clInfoBk (),

84 1. 1.4. VCL 85

1.4.34. TApplication () 1.4.35. TApplication ()



int HintPause MessageBox(const char * Text Caption
( 500 Text, const char * Caption, Flags
) int Flags = MB_OK) Application)>MessageBox( ,
int HintHidePause , MB_OK)
( 2500 ) ProcessMessages()
int HintShowPause
, BringToFront()
( 50 ).
,
TApplication .
TApplication , ,
TIcon Icon , . 
(Object Inspector)
AnsiString Title , . 
.
TForm* MainForm
TApplication.
bool ShowMainForm ,
. 
.
true , . 
AnsiString HelpFile . : , 
bool __fastcall TForm1::AppHelp(Word Command, long Data, . , OnActivate TNotifyEvent
bool &CallHelp) {Application)>HelpFile = Screen)>ActiveForm :
)>Name + .hlp; CallHelp = true;} typedef
void __fastcall TForm1::FormCreate(TObject void __fastcall (__closure *TNotifyEvent)(System::TObject* Sender);
*Sender){Application)>OnHelp = AppHelp;} TForm1 :
class TForm1 : public TForm
1.4.35. TApplication {
__published:
private: // .
Initialize() void __fastcall OnActivateHandler (TObject *Sender);
public:
Run() , };

CreateForm(TMetaClass* InstanceClass , , :
InstanceClass, void * void __fastcall TForm1::OnActivateHandler(TObject *Sender){
Reference) MessageDlg( !!!, mtInformation,
Terminate() . TMsgDlgButtons() << mbOK, 0);
};
,
Application)>Terminate() , .
Close() OnCreate , OnCreate TForm1 :
Minimize() C , void __fastcall TForm1::FormCreate(TObject *Sender){
Application->OnActivate = OnActivateHandler;
Maximize() };
Restore() Application->OnActivate 
OnActivateHandler.
86 1. 1.4. VCL 87

1.4.36. TApplication 1.4.37. TForm ()



OnActivate(TObject* Sender) , TFormBorderStyle
BorderStyle
OnDeactivate(TObject* Sender) , TCanvas* Canvas

OnException(TObject* Sender, , ) TRect ClientRect
SysUtils::Exception* E) E. ( ).
void __fastcall TForm1::FormCreate(TObject Rect(0,0,ClientWidth, ClientHeight)
*Sender){Application)>OnException = AppException;} ClientHeight
void __fastcall TForm1::AppException(TObject
ClientWidth
*Sender, SysUtils::Exception *E){ Application
TFormStyle FormStyle ,
)>ShowException(E); Application)>Terminate();}
fsNormal
OnHelp(Word Command, <F1>. CallHelp
int Data, bool &CallHelp) , WinHelp fsMDIForm
HelpFile,
Command Data fsMDIChild
OnHint(TObject* Sender)
fsStayOnTop
OnIdle(TObject* Sender,
bool &Done) . Done = true ( TBorderIcons BorderIcons ,
) .
, biSystemMenu
. False biMinimize

biMaximize
OnMinimize(TObject* Sender)
biHelp BorderStyle = bsDialog,
OnRestore(TObject* Sender)
TForm* ActiveMDIChild
OnSettingChange(TObject *

Sender, int Flag, const AnsiString . .
TForm* MDIChildren[int I]
Section, int &Result) C++Builder
int MDIChildCount

TModalResult ModalResult
TForm ShowModal(),
TForm.

(
TMainMenu* Menu
).
TWinControl* Parent ()
bool Visible ,
1.4.37. TForm TWindowState WindowState ,
:
bool Active , wsNormal ;
wsMinimized ;
TWinControl* ActiveControl () wsMaximized
88 1. 1.4. VCL 89

1.4.38. TForm 1.4.39. TForm ()



ArrangeIcons() OnShow(TObject* Sender) ,

Cascade() OnResize(TObject* Sender) ,
Next() OnPaint(TObject* Sender) ,
Previous()
Tile() OnKeyPress(TObject* Sender, Key
char &Key)
Close()
OnKeyDown(TObject* Sender, Key,
SetFocus()
Word &Key, TShiftState Shift) , Shift
SetFocusedControl

( TWinControl* Control. false, , OnKeyUp(TObject* Sender, Key
Control) true Word &Key, TShiftState Shift)
TBitmap* OnClick(TObject* Sender)
GetFormImage() void __fastcall TForm1::Button1Click(TObject *Sender) OnDblClick(TObject* Sender) ,
{
Graphics::TBitmap *FormImage = GetFormImage(); delete OnMouseDown(TObject* Button
FormImage; Sender, TMouseButton Button, (X, Y),
} TShiftState Shift, int X, int Y) Shift
Hide() , OnMouseMove(TObject*
Show() , Sender, TShiftState Shift, int X, (X, Y),
Release() int Y) Shift
int ShowModal() . OnMouseUp(TObject* Sender,
TMouseButton Button,
TShiftState Shift, int X, int Y)

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

1.4.44. TCanvas () 1.4.45. TPaintBox ()



Arc(int X1, int Y1, int X2, , , TFont* Font ,
int Y2, int X3, int Y3, (X1, Y1) (X2, Y2). TRect ClientRect
int X4, int Y4)
, TPaintBox. TPaintBox
(X3,Y3), , ,
(X4,Y4)
void OnPaint(TObject* Sender)
Chord(int X1, int Y1, int X2, Brush ,
int Y2, int X3, int Y3, int X4, , ) .
int Y4) (X1, Y1) ) (X2, Y2) , ,
(X3,Y3) (X4,Y4) . , 
Pie(int X1, int Y1, int X2, , , 
int Y2, int X3, int Y3, int X4, Chord , , 
int Y4)
. .
PolyBezier(TPoint* Points, , Points,
const int Points_Size) Points_Size TPaintBox TCanvas, 
PolyBezierTo(TPoint* , . TPaintBox
Points, int Points_Size)
Polyline(TPoint* Points, Points, void __fastcall TForm1::PaintBox1Paint(TObject *Sender)
const int Points_Size) Points_Size {
Polygon(TPoint* Points, , Points, PaintBox1->Canvas->RoundRect(20,20,180,100, 20,20);
int Points_Size) Points_Size , }

Brush . , TCanvas, ,
TextOut(int X, int Y, Text (X,Y), .
AnsiString Text) Font
TextRect(TRect &Rect, Text (X,Y), TMainMenu
int X, int Y, AnsiString Text) Rect
TMainMenu ()
int TextWidth(AnsiString , Text
, , 
Text)
int TextHeight(AnsiString , Text Microsoft Windows. 
Text) ,
TSize TextExtent TMainMenu TMenuItem* Items,
(AnsiString Text) Text . , 
struct TSize{long cx; long cy;} , , 
. .
TPaintBox
Menu Designer.
TCanvas 
TMenuItem. .
TPaintBox, TCanvas ,

, .
Caption, Enter. ,
, . 
1.4.45. TPaintBox
.
Create
TCanvas* Canvas Submenu, .
TColor Color , .
96 1. 1.4. VCL 97

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

TMainMenu TMenuItem. , TTimer. TTimer


TMenuItem
OnClick(TObject* Sender). :  OnTimer(TObject* Sender)
, , Interval ,
.... ,  Enabled true.
98 1. 1.5. 99

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;
};

TOpenDialog TSaveDialog. 1.5.



bool Execute();
C++ Builder
, , ,
. O
. 10
, FileName Files
( Borland
. :
Delphi v1.0), ,
if (SaveDialog1->Execute())
Memo1->Lines->SaveToFile(SaveDialog1->FileName); . , .
, 
, ,
1.4.4. .
, 1. . , ,
. 
(  . 
100 1. 1.5. 101

, , , . .  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

public: // User declarations Edit10->Font->Color = clBlack;


double A[7]; // F[9] = true;
double Xmin, Xmax; // }
int N; // catch (...) {
bool F[10]; // Edit10->Font->Color = clRed;
DynamicArray < double > Res; // F[9] = false;
}
F12, }
.
F[] OnCreate:
. Events
void __fastcall TMainForm::FormCreate(TObject *Sender)
OnChange. C++ Builder 
{
 for (int i=0; i<10; i++) F[i] = false;
. : }
void __fastcall TMainForm::Edit1Change(TObject *Sender) 
{ F[] 
TEdit* DataField = (TEdit*)Sender;
.
try { . 
double Num = StrToFloat(DataField->Text);
DataField->Font->Color = clBlack;
:
for (int i=0; i<7; i++) void __fastcall TMainForm::Button1Click(TObject *Sender)
if (DataField==FindComponent(Edit+IntToStr(i+1))){ {
A[i] = Num; //
F[i] = true; for (int i=0; i<10; i++)
} if (!F[i]){
TEdit* Temp = (TEdit*)FindComponent("Edit"+IntToStr(i+1));
if (DataField==Edit8){ Temp->SetFocus();
Xmin = Num; MessageDlg("!\n .",
F[7] = true; mtError, TMsgDlgButtons() << mbOK, 0);
} return;
if (DataField==Edit9){ }
Xmax = Num;
F[8] = true; for (int i=0; i<7; i++)
} if ((A[i]<-1)||(A[i]>1)){
} TEdit* Temp = (TEdit*)FindComponent("Edit"+IntToStr(i+1));
catch( ... ){ Temp->SetFocus();
DataField->Font->Color = clRed; MessageDlg("!\n A,B,...,G \n"+
" -1 1.",
for (int i=0; i<9; i++) mtError, TMsgDlgButtons() << mbOK, 0);
if (DataField==FindComponent(Edit+IntToStr(i+1))) return;
F[i] = false; }
};
}
, if ((Xmin < -50)||(Xmin >= Xmax)||(Xmax > 50)){
Edit8->SetFocus();
, ,  MessageDlg("!\n Xmin Xmax "+
, Edit2 Edit9,  "\n -50 < Xmin < Xmax < 50",
. mtError, TMsgDlgButtons() << mbOK, 0);
Edit10 : return;
}
void __fastcall TMainForm::Edit10Change(TObject *Sender)
{ if ((N < 2)||(N > 1000)){
try{ Edit10->SetFocus();
N = StrToInt(Edit10->Text); MessageDlg("!\n \n+
104 1. 1.5. 105

" 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;

// max min Res


double mYmin = Res[0];
double mYmax = Res[0];
for (int i=1; i<Res.Length; i++){
mYmin = min(mYmin, Res[i]);
mYmax = max(mYmax, Res[i]);
};

// , 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

,  Fortran MATLAB. API


. MATLAB  MATLAB ( ), MATLAB 
, . , MAT.

2.1.2.
(Toolboxes), 
. MATLAB
MATLAB (m), MATLAB MATLAB MATLAB. 
. ( 50) ( ) 
, ,  , , MATLAB.
, , , , ,  MATLAB . 2.1.1.
. MATLAB
MATLAB . :
MATLAB 6.5 ( 57 ) (Command Window);
1000 . (Workspace Browser);
(Array Editor);
2.1.1 MATLAB (Command History);
MATLAB . (Current Directory Browser);
. ,  (Start Button and Launch
MATLAB.  Pad);
. (Help Browser);
MATLAB , ,  / (Editor/Debugger);
 , ,  (Profiler).
. 1.
MATLAB. , Preferences File.
, ,  .
 (Command Window). , 
, , ,  m. 
. (>>).
MATLAB. ,  , .
, , , 
/  . , /
,  .
. (Workspace Browser). MATLAB
. MATLAB (), MATLAB
, . (. . 2.1.1).
MATLAB  , m
, ,  . 
. MATLAB , , . . 2.1.1. 
 who whos. who 
MATLAB. , whos .
MATLAB API (Application Program Interface,  , 
). , C Delete Edit,
112 2. MATLAB 2.1. 113

(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

Help MATLAB. Help,  , ,


? , ). ,
helpbrowser. Help
.
MATLAB. 
C:\MATLAB6p5\help\
begin_here.html, C:\MATLAB6p5\help\techdoc\ matlab_
product_page.html. 
, C:\MATLAB6p5\help\toolbox\symbolic\
symbolic.html symbolic_product_page.html.
MATLAB.
m.
help < m-> .
.
, help magic 
:
help magic
MAGIC Magic square.
MAGIC(N) is an N-by-N matrix constructed from the integers
1 through N^2 with equal row, column, and diagonal sums.
Produces valid magic squares for all N > 0 except N = 2.
MATLAB , 
. ,
. 2.1.4. Help) MATLAB matfun. 
: (Help Navigator), ,
, , . help matfun
help .
.  lookfor m ,
. , , ,
. , lookfor inverse 
, . , , :
. 2.1.4 Using the Symbolic Math Toolbox lookfor inverse
( ) , Function Reference INVHILB Inverse Hilbert matrix.
. Help : IPERMUTE Inverse permute array dimensions.
ACOS Inverse cosine.
Product filter ( ) ,  ACOSH Inverse hyperbolic cosine.
MATLAB; ACOT Inverse cotangent.
Contents () ; ACOTH Inverse hyperbolic cotangent.
Index () ; ACSC Inverse cosecant.
ACSCH Inverse hyperbolic cosecant.
Demos ( ) 
ASEC Inverse secant.
MATLAB; ASECH Inverse hyperbolic secant.
Search () ; ASIN Inverse sine. lookfor inverse
Favorites () ,  . ,
. :
.  computer , 
( MATLAB;
116 2. MATLAB 2.1. 117

info Math Works 2.1.3. MATLAB


;
ver MATLAB :
; i j ( 1);
version MATLAB; pi =3.141592653589793e+000;
what ; eps , 
what name , name; , eps = 2.220446049250313e
whatsnew name readme 016, 252;
name realmin , realmin =
; 2.225073858507202e308, 21022;
which name ; realmax , realmax =
help demos MATLAB; 1.797693134862316e+308, 21023;
bench .  inf ;
. ans , 
;
/. m,
NaN , (NotaNumber),
, MATLAB. / 
0/0.
m
. / File New, 
, MATLAB, 2.1.4. MATLAB
m. / MATLAB 15 ( ).
m , MATLAB , , .
Run. . 2.1.6.
. . 2.1.5, (%)  user classes java classes
. . Java.
/ ,
, m.
(Profiler).
, m. 
View Profiler MATLAB profile
viewer MATLAB.

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

sign(x) , 1, 0, +1; length(x)


ans =
rem(x,y) , x n.*y, n = fix(x./y);
4001
. 3. 
i j. z=a+bi  . , x=1:0.001:5
: ;, 4001 
z = a+bi = a +ib = a +i*b = a +b*i = a +bj = ... .
: 4. MATLAB 
abs(z) , |z|; , , ++.
conj(z) , abi; .
imag(z) ; , . ,
real(z) ;
angle(z) ; z=x(124)
isreal(z ) 1, 0  z = 1.1230
. z x(124) x.
:
2.2.2. linspace(a,b) 100 a b, 
a b;
, MATLAB . 
linspace(a,b,n) n [a, b]
double. , 
a b;
double 11. , x=1.5,
logspace(a,b,n) n [10a, 10b],
x, x(1), 
10a
x(1,1).
10b.


 , 
()
[]. ,
, []. ,
x=[1,2,3,4]
x=[1,2,3,4;5,6,7,8]
x=(1,2,3,4). x=[1,2,3,4] 
(1,2,3,4) (5,6,7,8).
: x=[1 2 3 4]. y=[x,5] x
: ,
5.
(;). 
(), 
, .
. , x(8)=1 
(), 
x 8, 1, 
. ,

x(3,1)=-1
x(8)=-1
x = , 1,
1 2 3 4 0 0 0 -1 .
z(10)=1.5 10, 10  , ( ) ,
1.5, . []. ,
. , 3 u, v, w n,
x=1:0.001:5; X=[u;v;w]
1 5 0.001.  Y=[u,v,w]
4001, .  3n u, v, w n3
u, v, w ( ).
124 2. MATLAB 2.2. MATLAB 125

[] ,  , () 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

Expr = sym('2*x+3*y'); % (138 ); >> digits(20);


x = sym('x'); % x (126 ); >> sym(pi,'d')
pi = sym('pi'); % (128 ); ans =
syms y z t; % y, z, t. 3.1415926535897931160
Symbolic Math sym  double(S) double.
. 
. . 
.  ezplot,
: (factor), (expand),  ezsurf.
(simplify), (solve),  5. y = sin(x)/x [10,10]
(det), (solve) z = x2 y2, x [10,10] y [5,5]:
. , x2 + 2x 10 = 0 syms x y
: ezplot(sin(x)/x,[-10 10])
ezsurf(x^2-y^2,[-10 10 -5 5])
solve(x^2+2*x-10,x)
ans = 
[ -1+11^(1/2)] . Symbolic Math
[ -1-11^(1/2)] digits vpa. digits
. (diff),  , , vpa, .
(int), (lim), 6. 45 :
(symsum taylor), digits(40)
vpa(exp(1))
(dsolve) . , :
ans =
I=int(sqrt(2-x^2),x) 2.718281828459045534884808148490265011787
I = 1/2*x*(2-x^2)^(1/2)+asin(1/2*2^(1/2)*x) vpa pi
ans =
. 3.141592653589793238462643383279502884197
sym
S = sym(A,flag) 2.2.5. ,
, flag f, r, e or d.

r. :
. MATLAB 
f .
1.F*2^(e) 1.F*2^(e), F 13 , M. M
e . : ,
ASCII. MATLAB /
>> S = sym(1/11,'f')
S = M, , MATLAB. /
'1.745d1745d1746'*2^(-4) File New,
r p/q, p*pi/q, sqrt(p), 2^q, and MATLAB. M, 
10^q p q. /, .m.
, M:  (m ) 
p*2^q p q. .
: . MATLAB
>> sym(1+sqrt(3),'r') . 
ans = .  
6152031499462229*2^(-51)
d .  .
digits. : 7. .
132 2. MATLAB 2.2. MATLAB 133

% :
% 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

A = fscanf(fid, 'format',size) 2.2.5.


size MATLAB,
fid. size \n
: \t
n n ; \b
inf ;
[n m] nm.
, fscanf ,  . 2.2.6.
MATLAB , size. MATLAB 
. format 2.2.6. fprint
.
() %-5.2d
2.2.4. (+) (+ ) %+5.2d
(0) %05.2d
%c
%d (. . 2.2.7).
%e, %f, %g (,
) 2.2.7. fprint
%i

%o
%s %c
%u %d ( )
%x %e ( 3.1415e+00)
%f
fprint. , %g ,
fopen. : %i ( )
%o ( )
fprintf(fid,'format',A)
%s
fid . %u ( )
. , . , %x (
fprint MATLAB , af)
. %X ( AF)
MATLAB 
. ,  9. dat.txt 
. (%)  A. , 6
: 5 .
(); fid=fopen('dat.txt','wt');
(); fprintf(fid,'%6.4f\t%6.4f\t%6.4f\t%6.4f\t%6.4f\n',A);
(). fclose(fid);
, %12.5e , 12 fprintf (
( ), 5 1), .
, , , 10.
. B = [8.8 7.7; 8800 7700]
, , fprintf(1,'X is %6.2f meters or %8.3f mm\n',9.9,9900,B)
(. . 2.2.5). :
136 2. MATLAB 2.3. 137

X is 9.90 meters or 9900.000 mm load filename X Y Z option X, Y, Z


X is 8.80 meters or 8800.000 mm , filename.mat (
X is 7.70 meters or 7700.000 mm
mat .mat MAT
);
2.2.7. load( 'fname') fname.mat.
MATLAB , ( ) load ,
. , 
. MATLAB .
. *, 
.  . , load demo*.mat
. demo, demol, demo2,
demoa, demob . .
.  .
. . ,
:
pack. diary filename.txt 
, ;
. diary off ;
. MATLAB  diary on .
 , diary off diary on, 
.mat. save,  . diary diary(' file
: name'), ' filename' . 
save [ ] [] []
: type filename
save filename exit, quit
filename.mat; (
save filename X X; finish.m) Ctrl+Q.
save filename X Y Z option X, Y Z. (, ) 
option, , . , exit save .
load
2.2.8. save , .

-append ) 2.3.
-ascii ASCII) (8 , ()
)
MATLAB. 
-ascii -double ASCII) (16 )
-ascii tabs , .
, 
-ascii -double tabs , , ,
-mat ) ( ) . MATLAB
.
, :
save('d:\myfile.txt','X','Y','-ASCII') 2.3.1.
( 
) load , save: , 
138 2. MATLAB 2.3. 139

0 255 (). , , t1='';


t2='';
MATLAB , :
t3='';
S= ' ' char(t1,t2,t3)
15, ,  ans =

. 127 ASCII,
, .
. ( 128 255) 310
, . .
S , .  double(S). S double.
''.  :
34 :
double('')
S=['abc ';'defg';'hi '] ans =
,  204 224 242 229 236 224 242 232 234 224
( 32 cellstr(S).
). S. S .
, , .
2.3.2. blanks(n). n . :
disp(['xxx' blanks(20) 'yyy'])
xxx yyy
. deblank(str). str.
char(X). X ( C deblank(C) 
0 65 535) MATLAB (  .
127 ASCII, 128 255 ASCII).
: 2.3.3.
char([33:38])
ans = ischar(S). , S 
!"#$%& , .
, , 255, , iscellstr(C). ,
rem(X,256) 256,  , .
fix(rem(X,256)). isletter(S) isspace(S). 
char(). S.
. ,
. cellstr. 2.3.4.
:
, , 
C=[{{''};};{''}];
, .
char(C)
ans = strcat(sl,s2,s3,...). 
s1, s2, s3, ...
. .
strvcat(t1,t2,t3....).
39 tl, t2, t3, ... S .
. strcmp( 'str1', 'str2'). . 
char (tl, t2, t). , , str1 str2 ,
t1, t2, t3.  . S T ,
. : TF = strcmp(S,T) , S,T, 
140 2. MATLAB 2.3. 141

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 =

summer : image, description date. date image: 'image2'


: year, description: ' '
date: [1x1 struct]
month day. ,
, (), (
) (). 2.5.2.
,
summer, .
152 2. MATLAB 2.5. 153

. , f = setfield(array, {array_index}, 'field', {field_index}, value)


(.) , . : size. size
str = summer(2).description . , 
str = size . array(n).field

size . ,
, size(summer)
. , 
summer 1 2
, ;
ans = 1 2
, . . ,
image nm,
2 3: size(summer(2).description)
n = summer(2).image(2,3) description summer(2):
,  ans = 1 14
. ,
, . . rmfield,
4. image : :
for i = 1 : length(summer) struc2 = rmfield(array, 'field'),
disp(summer(i).image)
array , 'field/ , .
end
image1 name patient
image2 summer = rmfield(summer, 'day');
, . 
. 
5. . .
11, . 
summer: . , 
B = summer(2) struct 
setfield getfield. ,  . 3
,  summer 11, :
. fieldnames , summer = struct('image', 'image2', 'description', ' ', 'date',
setfield getfield. struct('year', 2005, 'month',07, 'day', 22))
getfield : struct struct. 
f = getfield(array, {array_index}, 'field', {field_index}) .
array_index field_index ; 7. , 11. 
11.  struct:
getfield : A = struct('data',[3 4 7; 8 0 1],'nest',...
struct('testnum','Test 1','xdata',[4 2 8],'ydata',[7 1 6]))
f = array(array_index).field(field_index); A =
6. description  data: [2x3 double]
nest: [1x1 struct]
summer, getfield :
str = getfield(summer, {2}, 'description')
A(1) 
str = struct. ,
11:
setfield ,  A(1).data = [3 4 7; 8 0 1];
: A(1).nest.testnum = 'Test 1';
154 2. MATLAB 2.6. MATLAB 155

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

avg = mean(u,n); clear <_> ;


med = median(u,n);
clear functions ;
function a = mean(v,n) % Subfunction clear all .
% Calculate average. , ,
a = sum(v)/n;
, pcode :
function m = median(v,n) % Subfunction pcode newstats
% Calculate median.
 newstats.m 
w = sort(v);
if rem(n,2) == 1 () newstats.p. 
m = w((n+1)/2); .
else  newstats.m P newstats.p.
m = (w(n/2)+w(n/2+1))/2;
end
. P :
M
, MATLAB , 
, 
.
, ;
(private) 
, .
. , 
MATLAB. . M
.  , MATLAB. 
private .   .
 . MATLAB ,
, ,  .
MATLAB. ,  , 
,  .
. MATLAB . nargin nargout 
MATLAB, .
. 
. M . :
MATLAB M,  function c = testarg1(a,b)
, if (nargin == 1)
c = a.^2;
. , , MAT elseif (nargin == 2)
LAB : c = a + b;
; end
M;
, pri ; 
vate; .
MATLAB. , 
MATLAB  .  ,
4 . , . 
MATLAB  .
 . . MATLAB , 
 MATLAB
. . . , S=svd(A)
, clear . [U,S,V]=svd(A), 
. clear : . 
158 2. MATLAB 2.6. MATLAB 159

cat(A,B) A B. for k = 1:nargout


varargout{k} = arrayin(k,:) % Cell array assignment
, cat(A1,A2,A3,A4).
end
, 
, varargin varargout (va , for 
riable argument input, variable argument output). varargin . ,
, .  . testvar2
varargout .  :
varargin varargout  a = {1 2;3 4;5 6;7 8;9 0};
[p1,p2,p3,p4,p5] = testvar2(a);
. MATLAB
varargin varargout.
. varargin varargout 
,  . , 
, , . varargin varargout:
2. testvar  function[out1, out2] = example1(a,b,varargin)
function[i,j,varargout] = example2(x1,y1,x2,y2,flag)
, .
. M
function testvar(varargin)
for k = 1:length(varargin) ,
x(k) = varargin{k}(1); % Cell array indexing :
y(k) = varargin{k}(2); ,
end
xmin = min(0,min(x));
;
ymin = min(0,min(y)); 
axis([xmin fix(max(x))+3 ymin fix(max(y))+3]) ;
plot(x,y) , 
, testvar  , ; MATLAB
, : ;
testvar([2 3],[1 5],[4 8],[6 5],[4 2],[2 3]) 31 . , 
testvar([-1 0],[3 -5],[4 2],[1 1]) , MATLAB
varargin. varargin  31 .
, , M,
. ,  , 
: .
y(i)= varargin{i}(2); , 
{i} i  . 
varargin, (2) , .
. 4. , a b
varargout.  , :
varargout.
, 
nargout.
3. M lotka.m,
, x, .
y.  function yp = lotka(t, y)
%LOTKA - -
, testvar , global ALPHA BETA
function [varargout] = testvar2(arrayin) yp = [y(1) - ALPHA*y(1)*y(2); -y(2) + BETA*y(1)*y(2)];
160 2. MATLAB 2.6. MATLAB 161

, . 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

&& true (1), true, false (0), [i, j] = find(x) 


|| true (1), , . [i, j, s] = find(x) ,
true, false (0), , s.
MATLAB 
, , <matlab>\toolbox\matlab\ops\
A && B
A , false,  2.6.3.
B. B,
.

.  
MATLAB . :
xor(a, b). TRUE,  if , else elseif
TRUE, FALSE. ;
1, , . switch , case
all. 1, ( otherwise 
). , u ;
3?. while ,
u = [1 2 3 4];
, ;
v= all(u < 3) for , 
v= ;
0 continue for
all ,  while, ;
. break for while;
164 2. MATLAB 2.6. MATLAB 165

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

. MATLAB 7(R14) 3.1.1.


(dll) 87 ( MCRInstaller.exe). ()

C MATLAB . libmi.dll MAT)
libmmfile.dll M) MATLAB.
3.1.1. MATLAB m) MATLAB.
,
MATLAB C/C++ m) MATLAB
UNIX Windows Microsoft. C libmx.dll MATLAB.
MATLAB, . 
( MATLAB 6.5  libut.dll MATLAB . ,
, , 
mbuild.bat
Compiler).
, ,  compopts.bat mbuild.bat.
mbuild )setup
, mbuild.
C
<matlab>/extern/examples/cmath. mbuild.bat , , msvccomp.bat
C  Microsoft Visual C/C++
C/C++ . C/C++
: <matlab>\extern\lib\win32. (*.lib)
Microsoft Visual C/C++ 5.0 6.0; .
Borland C/C++ 5.0 5.02 (5.2); , MAT
Borland C++ Builder 3.0, 4.0, 5.0 6.0; LAB C/C++ Borland, Microsoft Visual C++ Watcom.
LCC, MATLAB 2.4. mglinstaller.exe, 
(dll), .
3.1.2. <matlab>\extern\include. 
MATLAB def , 
<matlab>. Microsoft Visual C Borland. ,
extern, , MATLAB, bin. lib*.def MSVC, _lib*.def Borland.
.
<matlab>\bin. 3.1.2. include
(DLLs), C, bat
mbuild, . libmatlb.h ,
<matlab>\bin . DLLs MATLAB
WIN32. libmmfile.h ,
M) MATLAB
3.1.1. matlab.h C
matrix.h , mxArray

libmat.dll MAT) mlfLoad() _libmat.def , MAT) DLL
mlfSave() libmat.def
libmatlb.dll MATLAB. _libmatlb.def ,
libmatlb.def MATLAB DLL
MATLAB. _libmmfile.def , )
libmmfile.def DLL m) MATLAB
174 3. 3.1. 175

3.1.2. include 3.1.4. MATLAB C



MATLAB
_libmx.def , libmx.dll
. /C++
libmx.def
MATLAB, MATLAB
<matlab>\extern\examples\cmath.  (.*) , (') 
C, C. C. MATLAB, 
, C, .
. : , MATLAB, :
intro.c ; mxArray;
ex1.c ; (+, *, /, );
ex2.c ; , MATLAB;
ex3.c ; .
ex4.c ; MATLAB 
ex5.c ; . , C
ex6.c Try/Catch; MATLAB:
release.txt MATLAB. ; 
UNIX Windows. ;
, , . .  MATLAB 1, 0, ;
*.dll : *.a IBM RS/6000; *.so Solaris, MATLAB , C
Alpha, Linux, and SGI; *.sl HP 700. ;
MATLAB ,
3.1.3. ;
MATLAB
MATLAB C .
C MATLAB .
HTML PDF ( MATLAB 6): MATLAB C
1) MATLAB C Math Library Users Guide ,  , C.
.
MATLAB Help; . , . 
2) MATLAB C Math Routine Reference MATLAB,
, Help MATLAB. 
C  . , 
MATLAB Function Reference  .
MATLAB . , C, , 
, MATLAB,  , C 
HTML <matlab>/help/mathlib/mathlib.html mathlib_product_ . C ,
page.html , , MATLAB C Math Library Users Guide. .
: MATLAB C. 
MATLAB C++ Math Library Users Guide; mxArray MATLAB.
MATLAB C++ Math Routine Reference. , 
helpdesk.html <matlab>/help/  , .
. mxArray . 
176 3. 3.1. 177

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

static double data[] = { 1, 4, 2, 5, 3, 6 }; ,


mxArray *A = NULL; :
mlfAssign(&A, mlfDoubleMatrix( 2, /* */ mlfOnes() ;
3, /* */
data, /* - */
mlfZeros() ;
NULL)); /* */ mlfEye() ;
mlfPrintMatrix(A); mlfRand() ;
mxDestroyArray(A); mlfRandn() ;
: mlfMagic() ( 2).
1 2 3 
4 5 6
.
, MATLAB , mlfOnes() 
C .  .
. MATLAB API mxCreateDoubleMatrix() , NULL.
.
mxArray *A = NULL;
, MAT mlfAssign(&A, mlfOnes( mlfScalar(2), mlfScalar(3), mlfScalar(2), NULL));
LAB API mxCreateNumericArray(). : mlfPrintMatrix(A);
; mxDestroyArray(A);
; :
, ; (:,:,1) =
. 1 1 1
1 1 1
, 33
2. mxDOUBLE_CLASS ,  (:,:,2) =
186 3. 3.2. mxArray 187

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);

/* Convert it into a cell array */


mlfCell() mlfAssign(&C, mlfNum2cell(N,NULL));
mlfCellstr()
mlfPrintMatrix(C);

mlfCellhcat() , mxDestroyArray(N);
mlfStruct2Cell() mxDestroyArray(C);
mlfNum2cell()
. , 
mlfCelldisp()
.
. 1 1 1
1 1 1
:
; [1] [1] [1]
; [1] [1] [1]
; MATLAB {} ( )
. . 
, mlfCell().  mlfCellhcat(). :
232 . mxArray *A = NULL;
mxArray *B = NULL;
mxArray *A = NULL; mxArray *C = NULL;
mlfAssign(&A, mlfCell(mlfScalar(2), mxArray *D = NULL;
mlfScalar(3), static double data[] = { 1, 4, 2, 5, 3, 6 };
mlfScalar(2),
NULL)); mlfAssign(&A, mlfColon(mlfScalar(1),mlfScalar(10),NULL));
mlfPrintMatrix(A); mlfAssign(&B, mxCreateString("my string"));
mxDestroyArray(A); mlfAssign(&C, mlfDoubleMatrix(2, 3, data, NULL));
:
(:,:,1) = mlfAssign(&D, mlfCellhcat(A,B,C,NULL));
[] [] [] mlfPrintMatrix(D);
[] [] []
mxDestroyArray(A);
(:,:,2) = mxDestroyArray(B);
[] [] [] mxDestroyArray(C);
[] [] [] mxDestroyArray(D);

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(&A, mlfStruct(mxCreateString("name"), /* */ category: 'tree'


mxCreateString("Polin"), /* */ height: 37.4000
mxCreateString("number"), /* */ name: 'birch'
198 3. 3.2. mxArray 199

, . 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

mxArray *func(mxArray **a, mxArray *b) mlfRestorePreviousContext(). 


. mlfRestorePrevious
mlfAssign(&b, mlfScalar(5)); Context(). return 
mlfAssign() b.  . ,
, b , mlfAssign() . , , 
. , . ,
5. mlfAssign() .  mlfRestorePreviousContext()
( mlfAssign())  mlfRestorePreviousContext() .
, :
. , void mlfRestorePreviousContext(int nout, int nin, ...);
mxArray *A = NULL; :
mxArray *B = NULL;
mlfRestorePreviousContext(1,2,output_arg1, input_arg1, input_arg2);
mlfAssign(&A, mlfRand(mlfScalar(4))); . mlfRestorePreviousContext()
mlfAssign(&B, A); ,
A B . , .
, NULL. mlfRestorePreviousContext()
. C , mlfEnterNewContext().
. 6. , mxArray **
, .  mxArray * . , char*
. int, , 
,  mlfEnterNewContext() .
. , , mlfRestorePreviousContext()
mlfScalar(), . :
mlfAssign(&B, mlfIndexRef(A, "(?,?)", mlfScalar(2), mlfScalar(2))); , 
mlfScalar(),  , ;
, mlfIndexRef() ,  , ,
. .
. : mlfRestorePreviousContext()
, mlfAssign(); , .
, . 7. mlfEnterNewContext() ,
mxDestroyArray() (mxArray*), . , 
: . , 
mxDestroyArray(A); , . mlfEnterNewContext()
A. mxDestroyArray() NULL. 
 . ,
. mxDestroyArray() .
mlfAssign(),  . ,
. , , return ,
mlfAssign (*C, mlfScalar (5)); mlfReturnValue(). ,
mlfAssign (*C, mlfScalar (6)); mlfReturnValue(), ,
mlfAssign() C ( 5)  , ,
C , 6. . mlfReturnValue()
210 3. 3.4. 211

. 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(&X, mlfIndexRef(, "(?)", B)) 1 4 7,


X: mlfIndexRef(A, "(?,?)", mlfCreateColonIndex(), mlfScalar(2))
8 3 :
4 3
4
 5
. : 6
mlfAssign(&B, mlfIndexRef(A, "(?)", mlfCreateColonIndex()));
 1 9. . mlfHorzCat(), mlfVertcat()
. N mlfIndexRef() mlfCreateColonIndex() ,
N , .  mxArray , 
, ,  , . , A([1 2],
mlfCreateColonIndex(). [1 3 2]) MATLAB)
.  1, 3, 2. :
N (N> 2),  mlfAssign(&B,
. mlfIndexRef(A, "(?,?)",
mlfHorzcat(mlfScalar(1), mlfScalar(2), NULL),
 mlfHorzcat(mlfScalar(1), mlfScalar(3),
, mlfScalar(2), NULL)));
mlfAssign(&B, , ( ) 1 2. 
mlfIndexRef(A, "(?,?)", mlfScalar(2), mlfScalar(2)));
:
5 A ( 2, 2). 1 7 4
2 8 5
, .  , .
mlfHorzcat(), mlfVertcat() mlfCreateColonIndex() :
, , ; . 2
mxArray, , 3.
. :
mlfAssign(&B, , . , B
mlfIndexRef(A, "(?,?)", :
mlfHorzcat(mlfScalar(1), mlfScalar(3), NULL),
mlfScalar(2))); 1 1
2 3
( ) 2:

4
6 mlfIndexRef(A, "(?,?)", B,
mlfHorzcat(mlfScalar(1), mlfScalar(2), NULL))
, 
A(B,[1 2]) MATLAB ,
. ,
, 1 2:
mlfAssign(&B,
mlfIndexRef(A, "(?,?)", 1 4
mlfScalar(2), 2 5
mlfHorzcat(mlfScalar(3), mlfScalar(3), NULL))); 1 4
3 6
B (2,3): B = [8, 8]. , 
. :
mlfCreateColonIndex() , 
mlfIndexRef(A, "(?,?)",
: mlfHorzcat(mlfScalar(2), mlfScalar(3), NULL),
mlfIndexRef(A, "(?,?)", mlfScalar(1), mlfCreateColonIndex()) mlfCreateColonIndex())
218 3. 3.4. 219

A([2 3],:) MATLAB  mlfAssign(&X, mlfIndexRef(A, "(?,?)", B, C));


:
2 5 8 4
3 6 9 6
. B ,
n . ,  . C
.  , ,
, . 1 3.
. .
(mlfLt(), mlfIndexAssign(). (
mlfGt(), mlfLe(), mlfGe(), mlfEq(), mlfNeq()) mlfLogical().  , ), , 
.  , . 
. ,  : , , , , 
mlfAssign(*B, mlfLogical(matrix)), . n
matrix .
(n > 2). 
, .
.
N , 
,
, , . 
. :
A
mlfIndexAssign(&A, "(?,?)", mlfScalar(2), mlfScalar(1),
1 4 7
mlfScalar(17));
2 5 8
3 6 9 2 1 17. ,
B ( ) , 
1 0 1 , .
0 1 0 
1 0 1 . ,
, . ,
.  mlfIndexAssign(&A, "(?,?)", mlfScalar(2), mlfCreateColonIndex(),
.  mlfColon(mlfScalar(1),mlfScalar(3),NULL));
. , B , 33 1 2 3. 
A, A :
mlfAssign(&X, mlfIndexRef(A, "(?)", B)); 1 4 7
1 2 3
1 3 6 9
3 .
5
7
. , B = [1 2] C = [2 3],
9 source [1, 4; 6, 7].
, mlfIndexAssign(&A, "(?,?)", B, C, source);
, . 22 source 1 2: 
MN A.  A. A :
 1 1 4
, . 2 6 7
, B = logical([1 0 1]) C = logical([0 1 0]), , 3 6 9
, . mlfIndexDelete().
220 3. 3.4. 221

 . 
,  , ; 
, . , :
, ,  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

mlfAssign(&str, mlfIndexRef(summer, (?).image, mlfScalar(2))); second_date = c{1}(2).date MAT


. image = summer(2).image  LAB. date.
MATLAB. . ,
. : () 
, , . , ,
, , .
. ,
: mlfIndexDelete(). ,
mlfAssign(&n, mlfIndexRef(summer, , 
"(?).image(?,?)",
mlfScalar(3),
:
mlfScalar(1), mlfIndexDelete(&summer, "(?)", mlfScalar(2));
mlfCreateColonIndex()));
.
n = summer(3).image(1,:) MATLAB.
. mlfRmfield(). ,
( , )  :
mlfIndexAssign(). , mlfAssign(&summer, mlfRmfield(summer,
, : mxCreateString("description")));
mlfIndexAssign(&summer, , rmfield() 
"(?).description",
mlfScalar(17), . mlfIndexDelete()
mxCreateString(" 1")); , . ,
, mlfIndexAssign() , 
mxArray **, mxArray *, mlfIndexRef(). mlfIndexDelete():
mlfIndexAssign(), ,  mlfIndexDelete(&summer, "(?).image(?,?)",
. mlfScalar(3),
mlfCreateColonIndex(),
. mlfScalar(5));
.
summer(3).image(:,5) = [] MATLAB.
. , , ,
, . , 
mlfIndexRef(). date  3.5.
:
mlfAssign(&y, mlfIndexRef(summer,"(?).date.year",mlfScalar(2)));
MATLAB 
. MATLAB
y = summer(2).date.year MATLAB.
,
, mlfIndexAssign()
varargin varargout. C
mlfIndexRef().
,
, . 
, , ,  . , MATLAB 
. .  C ,
mlfIndexRef() . . . 
, c  
. , .
: , 
mlfAssign(&second_date, mlfIndexRef(c, "{?}(mlfScalar(2)).date", , . Help MATLAB 6: MATLAB C Math Libra
mlfScalar(1))); ry Reference.
226 3. 3.5. 227

3.5.1. MATLAB mxArray (mxArray ** ).


.
MATLAB,  , mlfFind() 
, C , mxArray** , 
. , MATLAB cos . mlfFind :
, mlfAssign(&k, mlfFind(NULL,NULL,X));
Y = cos(X); mlfAssign(&i, mlfFind(&j,NULL,X));
mlfAssign(&i, mlfFind(&j,&v,X));
X Y . , 
i, j, k, v, X mxArray* , i, j, k, v NULL.
:
. 
mlfAssign(&Y, mlfCos(X));
mxArray*, . 
X Y mxArray . Y mxArray** .
NULL. mlfAssign() . MATLAB
mlfCos() Y. . , MATLAB
1.  svd , , 
. .
. MATLAB
s = svd(X)
. , tril,  [U, S, V] = svd(X)
, , [U, S, V] = svd(X, 0)
. k, , , svd . 
, k = 0 ( , X 
k ) , . . X , (U, S,
MATLAB tril V, 0) .
L = tril(X) L = tril(X,k), mlfSvd , 
L, X, k , k 11 . C  MATLAB svd. 
, mlfSvd . U 
tril .  .
. , NULL. mxArray*, mxArray **.
tril : mxArray *mlfSvd(mxArray **S, mxArray **V, mxArray *X, mxArray *Zero);
mlfAssign(&L, mlfTril(X,NULL)); S V 
MATLAB svd. X Zero
mlfAssign(&L, mlfTril(X,k)); svd. MATLAB svd 
L, X, k mxArray. L . 
NULL mlfAssign(). :
. MATLAB mxArray *X;
mxArray *U = NULL, *S = NULL, *V = NULL ;
. ,
find,  mlfAssign(&S, mlfSvd(NULL, NULL, X, NULL));
, , . mlfAssign(&U, mlfSvd(&S, &V, X, NULL));
mlfAssign(&U, mlfSvd(&S, &V, X, mlfScalar(0)));
k = find(X); /* X(:) */
[i,j] = find(X); /* */ , mlfSvd ,
[i,j,v] = find(X); /* */ NULL. NULL
C . .
. . MATLAB vjuen
find . . varargin
228 3. 3.5. 229

. 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

mlfVarargout(&z, &m, &n, NULL), a, b); mlfVarargout() mlfIndexVarargout() 


mxArray* . x  ;
, y . z, m, n NULL ,
mxArray* varargout. a b ;
. , varargout. C .
MATLAB : , 
[x, y, z, m, n] = mlfVarargout_Function(a, b); ;
. , NULL ,
varargout ,  .
, varargout mlfVarargout_Function, . ,
mlfindexVarargout() . . NULL
MATLAB .
[x, y, z(1), m, n{:}] = mlfVarargout_Function(a, b) . mlfLoad(), mlfSave() mlfFeval() 
. mlfLoad()
mxArray *x = NULL, *y = NULL, *z = NULL, *m = NULL, *n = NULL;
mlfSave() . 3.6 .
ex3.c. <matlab>\extern\examples\cmath 
mlfAssign(&x, mlfVarargout_Function(&y, , , 
mlfIndexVarargout(&z, "(?)", mlfScalar(1), . mlfSvd
&m, NULL,
&n, "{?}", mlfCreateColonIndex(), .
NULL), a, b)));
. 3.5.2.
, 
. ,  , . 
, 
. , ,
, . f(x) 
,  . 
.  , ,
. . ,
. :  g(f(x)), yi = f(xi)
, , varargout mlfVarargoutList zi = g(f(xi)). 
(varargout ), , . , 
(varargin). .
x(t) = F(x(t),t) x(ti+1)
MATLAB  F(x(ti), ti). 
: mlfFeval().
MATLAB min(f(x))
mlf; f(x). 
MATLAB. MATLAB f(xi) .
. , f(x)
; , min . 
; mlfOde 
. , mlfOde23(), mlfDblquad,
, mlfQuad, mlfQuad8 mlfFzeros(), mlfFmin(), mlfFmins(), mlfFoptions.
232 3. 3.5. 233

: Thunk mlfFeval(). Thunk


mlfFeval()? , mlfFeval() ( 
mlfFeval()? ), C ( 
mlfFeval() thunk ? ), mlfFeval().
mlfFeval().  mlfFeval().
mlfFeval() . mlfFeval() :
, mlfOde23() (ex4.c) 1. , .
mlfFeval() lorenz(). 2. thunk, , .
, mlfFeval() . 3. :
, lorenz,  , thunk
mlfFeval() , mlfOde23(). .
4. mlfFeval().
, mlfFeval(), 
, mlfFeval()  thunk. Thunk :
. , mlfFeval() , 
, , ;
. ;
mlfFeval() , ;
mxArray *mlfFeval(mlfVarargoutList *varargout,
.
void (*mxfn)(int nlhs, mxArray **plhs, 4. thunk
int nrhs, mxArray **prhs), , thunk 
...);
.
(prhs) . (ex4.c). 
(plhs)  mlfOde23()
(nrhs nlhs) (name)
mlfFeval(), . (
mlfFeval(). , <matlab>\extern\examples\cmath). F
mlfFeval() : mlfOde23() 
, . y = F(t, y) . mlfOde23() 
, . mlfFeval()  ,
, ,   . F
. mlfFeval() : lorenz.
, ;
, thunk.

. , mlfFeval() , ,
.  . ex4.c
, mlfFeval(). . 
thunk , , , ,
. ex4.c thunk _lorenz_thunk_ , lorenz.
fcn_ lorenz(). thunk  /* ex4.c */
, .
#include <stdlib.h>
,
#include matlab.h /* */
, thunk.
mlfFeval() thunk . double SIGMA, RHO, BETA; /* */
234 3. 3.5. 235

/* 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

2. lorenz. lorenz  mlfFevalTableSetup( MFuncTab ); /* 1 */


thunk mlfFuncp, ,  SIGMA = 10.0; /* */
. mlfFuncp : RHO = 28.0;
typedef void (*mlfFuncp)(void) BETA = 8.0/3.0;
, ,  mlfAssign(&tsm, mlfDoubleMatrix(2, 1, tspan, NULL)); /* 2 */
, lorenz. mlfAssign(&ysm, mlfDoubleMatrix(1, 3, y0, NULL));
pFunc , . PFCN_1_2
mlfAssign(&tm, mlfOde23(&ym, mlfVarargout(NULL), /* 3 */
, 1
mxCreateString("lorenz"), tsm, ysm, NULL, NULL));
2 .
3. , . n = mxGetM(tm); /* */ /* 4 */
lorenz . t = mxGetPr(tm);
y1 = mxGetPr(ym);
thunk , y2 = y1 + n;
. , thunk y3 = y2 + n;
, .
4. lorenz, pFunc, mlfPrintf(" t y1 y2 y3\n"); /* 5 */
for (k = 0; k < n; k++) {
lorenz, PFCN_1_2. , . mlfPrintf("%9.3f %9.3f %9.3f %9.3f\n",
, t[k], y1[k], y2[k], y3[k]);
(rhs[0]) ; }
NULL. ,  /* */
mxDestroyArray(tsm);
(rhs[1]) ; mxDestroyArray(ysm);
NULL . lorenz  mxDestroyArray(tm);
Out. mxDestroyArray(ym);

mlfRestorePreviousContext(0,0);
. , , return(EXIT_SUCCESS);
lorenz .  }
thunk. :
, lorenz  1.
, thunk. feval mlfFevalTableSetup().
5. , lorenz  MFuncTab "lorenz" lorenz
. thunk lorenz. mlfOde23() mlfFeval(),
lhs[0].  mlfFeval() 
, lhs[1], lhs[2] . . , ,
6. . , "lorenz".
( 2. mxArray, tsm ysm,
, ) mlfOde23. 
int main( ) tspan y0.
{ 3. mlfOde23(). 
/* */
mxArray *tm = NULL, *ym = NULL;
. mlfOde23() a varargout
mxArray *tsm = NULL, *ysm = NULL; , mlfVarargout(NULL) , varargout
double tspan[]={0.0, 10.0}; /* */ . ,
double y0[] = { 10.0, 10.0, 10.0 }; /* y0 */ , NULL 
double *t, *y1, *y2, *y3;
int k, n; .
mlfOde23() mlfFeval() lo
mlfEnterNewContext(0, 0); renz. mlfFeval()
238 3. 3.6. 239

. , 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

Microsoft Visual C/C++ 5.0 6.0; <matlab>\extern\lib\win32. (*.lib)


Borland C/C++ 5.0 5.02 (5.2); .
Borland C++ Builder 3.0, 4.0, 5.0 6.0; , MAT
LCC, MATLAB 2.4. LAB C++ Borland, Microsoft Visual C++ Watcom.
, MATLAB C/C++  C++ 
. C++ M. .
C++. . mglinstaller.exe 
,  (dll), 
C++. . , . 4.1.2.

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

<matlab>\extern\include\cpp. C++ helpdesk.html <matlab>/help/ 


C++: .
matlab.hpp MAT
LAB C++; 4.1.4. MATLAB C++
version.h C++;
C++ MATLAB,
mathwork.h .
MATLAB, (.*),
<matlab>\extern\examples\cppmath.  , , (), C++.
C++, MATLAB . ,
MATLAB. MATLAB C/C++ (:) C++, colon():
Math Library . : A(colon(2,5), colon(1,6));
ex1.cpp  ; MATLAB C++
ex2.cpp ; MATLAB . , , ,
ex3.cpp ;  C++. , 
ex4.cpp ; MATLAB:
ex5.cpp ; MATLAB mwArray;
ex6.cpp / ; (+, *, /, - .);
ex7.cpp load() save(); () , MATLAB;
ex8.cpp m roots.m C++. MATLAB C++ .
UNIX Windows. ,
, , . .  MATLAB . MATLAB 
*.dll : *.a IBM RS/6000; *.so Solaris, Alpha, Linux, C++. MATLAB MATLAB
and SGI *.sl on HP 700. /C++ :
/C++. 
4.1.3. :
MATLAB 1, 0, /C++;
MATLAB C++ MATLAB , /C++
;
MATLAB ;
HTML PDF ( MATLAB 6):
MATLAB
1) MATLAB C++ Math Library Users Guide , 
, /C++ ;
. 
/C++ (if, for, and while)
Help MATLAB;
MATLAB;
2) MATLAB C++ Math Routine Reference  /C++ . MATLAB
C++, Help .
MATLAB. C++  ;
MATLAB Function Reference MATLAB
MATLAB. .
, MATLAB,  C++
HTML <matlab>/help/mathlib/mathlib.html mathlib_product_ . C++ ,
page.html , , MATLAB C++ Math Library Users Guide. .
: MATLAB, 
MATLAB C Math Library Users Guide; .
MATLAB C Math Routine Reference. , C++ .
250 4. 4.1. 251

(if, for MATLAB, , 


while) MATLAB /C++ . , MATLAB C++, 
, , .
/C++ . if while  . ,
, tobool() ,  MATLAB. ,
, , , 
. C++. , , 
, C++, ,  . MATLAB : 
, C/C++ . C++
. C/C++ , + .
, . , , , A*B 
( ) A B, A B.
4.1.5.
.
MATLAB C++ C++ .
MATLAB , , , +
C++. .  , .
. . C++ 400 
. MATLAB, C++  . C++
. mwArray. MATLAB, , 
, MATLAB, C++ , 17,  .
, 11, C++, MATLAB 
. .
C++ ,  , ,
, . C++ , .
. . ,
mwArray MATLAB [V, D] = eig(X)
MATLAB. mwArray C++
MATLAB. MATLAB  V = eig (&D,X);
, ( ) ( ,  MATLAB ,
) .  .
. , C++. , 
.  , . 
. , . sqrt() , sqrt() .
mwArray .  . MATLAB fscanf() fprintf()
C++ mwArray. / load() save() 
, mwArray . MAT MAT.
4.6 . MATLAB fscanf() fprintf()
MATLAB C++ load() save()
: mwIndex mwSubArray.  C++ .
. mwIndex ,  , , fprintf(),
, mwSubArray  , . C++
. . mwIndex 4.3 . , cin, cout, cerr. cin , cout
252 4. 4.1. 253

cerr . C++, m


A , : C++ C++ . 
cout << A << endl; MATLAB 
: M C++. :
cin >> A; MATLAB ;
A , : MATLAB C++;
MATLAB C++ 
cerr << A << endl;
;
. MATLAB C++ 
C++ ,
C++, . 
, , , .
. mwException.  1. (ex4.cpp).
,  , , 
. : . 
try { <matlab>\extern\examples\cppmath.
// // ex4.cpp
} //
#include <stdlib.h>
catch(mwException &ex) { #include "matlab.hpp" // #1
cout << ex << endl;
} //
static double data0[] = { 2, 6, 4, 8 }; // #2
trycatch ,  static double data1[] = { 1, 5, 3, 7 };
, 
, . // average(), "" .
. MATLAB  mwArray average(const mwArray &m1, const mwArray &m2) // #3
, MATLAB . {
MATLAB .  return rdivide(plus(m1, m2), 2); // (m1+m2)/2
}
MATLAB C++ 
, . // main(). mat0 mat1,
// mat2,
4.1.6. ++, // average() .

M, MEX, MATLAB. int main(void) //#4


{
C++  // Create two matrices
. MATLAB, , mwArray mat0(2, 2, data0); // mat0 = [ 2 4; 6 8 ] #5
, MATLAB . mwArray mat1(2, 2, data1); // mat1 = [ 1 3; 5 7 ]
. mwArray mat2;
Handle Graphics, mat2 = average(mat0, mat1); // #6
MATLAB Simulink. ,
MATLAB R14. cout << mat0 << "\t + \n" << mat1
<< "\t / 2 = \n" << mat2; // #7

. . return(EXIT_SUCCESS);
C++ }
. , 
m MATLAB. :
254 4. 4.1. 255

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++ mbuild [-options] filename1 [filename2 ...]


C++. C++  mbuild . 5.2.1 5.
mbuild .  .
C  ,
( DOS MATLAB): C++, MathWorks 
mbuild filename.cpp C++.
, C++, mbuild  , , :
.  , , bin, mbuild
.  , ;
C MEX, ;
MATLAB, 
mbuild -setup
.
setup mbuild 
C++
compopts.bat . 
mglinstaller.exe , 
compopts.bat
, 
. . 4.1.5 , 
MATLAB. 
MATLAB C++ Math Library. ,
.
mbuild ,
<matlab>\extern\lib\win32\mglinstaller.exe.
v

mbuild-v filename1 [filename2 ...]
MATLAB mglinstaller.exe. 
,  . ,
mbuild. \bin\win32 (PATH).

4.1.4. PC MATLAB, , .
, .
Borland C/C++, Version 5.0 bcccompp.bat UNIX.
Borland C/C++, Version 5.2 bcc52compp.bat UNIX , 
Borland C++Builder 3.0 bcc53compp.bat Help MATLAB. , 
Borland C++Builder 4.0 bcc54compp.bat MATLAB: $HOME/.matlab/R12/mbuildopts.sh <matlab>/bin/
Borland C++Builder 5.0 bcc55compp.bat mbuildopts.sh. mbuild UNIX PC .
Lcc 2.4 (bundled with MATLAB) lcccompp.bat UNIX C/C++
Microsoft Visual C/C++, Version 5.0 msvc50compp.bat
(.so) (.sl).
Microsoft Visual C/C++, Version 6.0 msvc60compp.bat

C/C++ (SHLIB_PATH, LIBPATH LD_LIBRARY_PATH).
MATLAB 6.0 
, 
C, C++ .
,
C++ f:
. , 
mbuild -f <file> ...
, bin/$ARCH
f mbuild <file> LD_LIBRARY_PATH.
mbuild, 
. <file> , <file> 
.
4.2. mwArray
mbuild ,  , . 
. mbuild: 
258 4. 4.2. mwArray 259

. 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

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


mwArray C(2, 4, data); //
C++ 
mwArray D(C); // C . ,
, . 
cout << "C =" << C << endl; , 44
cout << "copy of C =" << D << endl;
44 C.
. 
mwArray A, B;
MATLAB C++ ,  A = ones(4);
MATLAB: B = randn(4);
ones() , ; mwArray C = A * B;
zeros() , ; C , .
empty() ; . MATLAB ([]) 
eye() ( 2); .
rand() ; C++ , :
randn() ; horzcat() ;
magic() ( 2). vertcat() .
. n , 1, 2, 3 4
n. , :
 mwArray A;
233. A = horzcat( 1, 2, 3, 4 );
mwArray B; C++, vertcat(),
B = randn(2,3,3); // mwArray A;
2. . A = vertcat( horzcat(1, 2), horzcat(3, 4) );
. horzcat() .
:
(Integer Ramps). MATLAB (:) A = [
.  1 2 ;
3 4
]
MATLAB.
horzcat () vertcat () 
(:):
, . , 
ramp() ;
A B C.
colon() .
mwArray A = vertcat( horzcat(1, 2), horzcat(3, 4) );
MATLAB, colon() mwArray B = vertcat( horzcat(5, 6), horzcat(7, 8) );
for C++.  mwArray C = vertcat( A, B );
colon()  ;
. 4.3. .
ramp(),  horzcat() vertcat()
, .  .
1 13. cat(). :
mwArray A = ramp(1,13); mwArray B = cat(dim,A1,A2...)
ramp() , A1, A2 . . mwArray, dim 
,  , . ,
. ++:
262 4. 4.2. mwArray 263

mwArray A = vertcat( horzcat(1, 2, 3), horzcat(4, 5, 6) ); C++ , 


mwArray B = vertcat( horzcat(11, 12, 13), horzcat(14, 15, 16) );
:
mwArray C = cat( 3, A, B );
static double data[] = { 1, 4, 2, 5, 3, 6 };
cout << "C =" << C << endl; mwArray A(2, 3, data);

: .
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.

MATLAB 16 Unicode.


:
4.2.4.
mwArray; MATLAB 
; MATLAB. 
.
C++:
MATLAB ,
cell() ;
C++
cellstr() ;
mwArray.
cellhcat() 
mwArray A("my string");
;
cout << "A = " << A << endl; struct2cell() ;
: num2cell() ;
'my string'
celldisp() .
( ) , MATLAB C++
char_func(). :
. ;
;
mwArray C,D;
C = horzcat(109,121,32,115,116,114,105,110,103); ;
D = char_func(C); .
cout << D << endl;
cell() MATLAB C++,
: . 
'my string' . cell() 
. 232.
, double_func(). , MATLAB .
268 4. 4.2. mwArray 269

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

4.2.4 , 4.2.5. mwArray ()


mwArray. 
. C++ 
Double double x; double x;
. , mwArray A = 5; mwArray A = 5;
. C++ , x = A; x = (double)A;
. ,
, C++ , , mwArray. C++ 
. , 
mwArray.
4.2.4. mwArray mwArray.
GetData().
mwArray A; mwArray A; GetData(), .
A = 5; A = mwArray(5) mxArray *. ,
mwArray A; mwArray A; .
A = "abcd"; A = mwArray("abcd");
.
Available mwArray A;
doubles static double x[]={1,5}; , C++
A = mwArray(1,2,x); , mxArray *, mxGetPr() (
mwArray A; mwArray A; ) mxGetPi() ( 
mxArray mxArray *mat; mxArray *mat; ). GetData ():
A = mat; A = mwArray(mat);
mwArray A = magic(10);
mwArray A, B; mwArray A, B; double *real_data = mxGetPr(A.GetData());
mwSubArray B = ramp(1,10); B = ramp(1,10);
mwSubArray sub=B(8); mwSubArray sub = B(8); 5. ,
A = sub; A = mwArray(sub); GetData (), mxGetPr () mxGetPi ().
, 
MATLAB . mwArray  , mwArray.
: .
; mxArray . 3,
MATLAB mxArray. <matlab>/extern/include/matrix.h, : MAT
4.2.5 , mwArray.  LAB Application Program Interface Guide.
(mxArray),  SetData(). GetData() SetData(), 
mwArray, . , , mwArray.
, . SetData() , 
const, , . mwArray, , 
. mwArray . ,
C++ (int double).  mwArray, GetData() mwArray:
mwArray ( ) . mwArray A = rand(4), B = magic(10);
B.SetData(A.GetData()); // .
mwArray 6. , ,
mwArray, real() imag(). SetData(). mwArray
, .
4.2.5. mwArray ExtractScalar() ExtractData(). ExtractScalar() Extract
Data() ,
Integer int32 i; int32 i; mwArray. ExtractScalar() 
mwArray A = 5; mwArray A = 5; .
i = A; i = (int32)A; ExtractData() C++ .
274 4. 4.2. mwArray 275

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

mwArray::Size(); C++ , . C++


mwArray::EltCount(). MATLAB C++. ,
size(): , 
mwArray A = rand(4,7) ;
, , ,
mwArray m, n; MATLAB. C++ 
size(mwVarargout(m,n), A); :
size() MATLAB ([]),
. mwArray,
MATLAB, size() . vertcat() horzcat();
, .*, .\, ./, .^, \, "" (') " 
, size(), " (.') ++, 
. C++;
size(): (:) , colon() ramp();
mwArray A = rand(4,7); {},
int m, n; mwArray::cell();
m = size(&n, A); (.) , 
size() , mwArray::field().
. size() , C++
.  .
mwArray::Size(), . , C,
mwArray::Size(). mwArray
.
, ,
mwArray. mwArray 
mwArray. 
mwArray (mwArray &).
. 
C++, MATLAB if, for while. 
, . :
C++ MATLAB .
int32 dims[2];
, MATLAB end for, C++ 
int32 ndims[3];
.
mwArray A = rand(4,7); // C++ MATLAB for, 
mwArray B = rand(4,7,4); // . C++ for
A.Size(dims); // dims (4, 7)
. MATLAB 
B.Size(ndims,3); // ndims (4, 7, 4) . for 
A.Size(); // : 2 . MATLAB ,
A.Size(1); // 1- : 4 . C++ , 
A.Size(2); // 2- : 7
, . 
mwArray EltCount(). ,  C++, MATLAB.
, mwArray , EltCount().  MATLAB ,
, . 
: logical() .
A.EltCount(); // : 28 C++ . mwArray 11
m ++. MATLAB  . ,
m MATLAB ++.  , C++ .
, MATLAB C++  ( ), 11.
MATLAB, m () 
MATLAB "" ++. MATLAB , tobool()
278 4. 4.3. 279

MATLAB C++, .  4.3.1.


tobool() 
. if while C++  MATLAB
. MATLAB, C++ . , 
(<, >, <=, > =, == != ) ,  . A
 . , A(3) 
if while tobool(). , , .
A , : , MATLAB
if (tobool(A != 0)) , . 
{ , [d1 d2], 
// test succeeded, do something
(i,j) a(i,j) k 
}

: ,
k = (j-1)*d1+i
tobool() ,
, , double. ,  , A(3,2) MATLAB k = (2
. 1)*3+3 = 6. 
m ++  .
. MATLAB , ex8.cpp, m ++. .
, m roots.m C++. , , ,
roots(), m roots.m, . colon(). 
C++, m,  . , 
. C++ , , .
, C++ , M A :
MATLAB. (ex8.cpp) A =
<matlab>\extern\examples\cppmath. 1 4 7
2 5 8
4.3. 3 6 9
.
MATLAB C++ , ,
MATLAB.  A(5)
, n ,
A, 5.
, ,
,
.
. :
MATLAB : ,
. : , A(horzcat(2,5,8))
(); ,  , A, 2, 5, 8.
{}; ,  13,  13.
. C++ 
. : A(vertcat(2,5,8))
() ; A, ,
mwArray::cell() ; vertcat() .
mwArray::field() . ,
() mwArray::cell()  ,
, . . MATLAB end, 
mwArray::field() . . , A(6:end) 
280 4. 4.3. 281

A(6) . end(A, k, n)  end() . 


, k , , , 3:
, n . end(A, k, n) A(3, colon(2, end(A, 2, 2)));
k n.  A(3, 2:end) MATLAB. 2 end()
C++ , , , end(), .
A, A(6:end) MATLAB: 2 ;
A(colon(6, end(A, 1, 1))) 2. 6, 9 A.
(1) end() .  , colon()
(1) ,  . , A(1, colon()) :
. 6, 7, 8, 9 A. 1 4 7
colon().  , 
. , A(colon())  . horzcat(), vertcat()
. colon()
, .  mwArray, . :
, , , A(horzcat(1,2), horzcat(1,3,2))
. , B :
, ( )
1 2
.
3 2
. 
A(B) A, () . 
1, 3, 2, 2. ,  . , , :
:
1 1
1 2 2 3
3 2
A(B, horzcat(1, 2)) , ,
. N n . 1 2:
, , . .
1 4
, , 2 5
colon().  1 4
n ( n > 2).  3 6
. A. , 
,  colon() . :
. , A(2,2) 5 A ( , A(horzcat(2, 3), colon())
). 2 3:
, 2 5 8
. horzcat(), vertcat() 3 6 9
colon() .
mwArray, . , n . , 
A(horzcat(1,3),2) ( . 
) 2: , ,
4 .
6 (<, >, <=, >=, ==, !=) logical().
, 
. , A(2, horzcat(3, 3)) , 
A(2,3) 8, 8. .
282 4. 4.3. 283

, ,  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 second_date = c{1}(2).date . double x = (rand(4)*rand(4))(2,2);


. .
, mwIndex. mwIndex , 
. ,  , (, , ) 
, . . . 
, 
. ,  .
, : mwIndex . 
summer(2) = empty(); colon(). , mwIndex
images(2) = [] MATLAB.  colon(). , 
. mwIndex ( )
rmfield().  mwIndex, (:).
, description 
: 4.3.1. mwIndex colon()
summer = rmfield(summer, "description"); C++
3. rmfield() MATLAB colon() mwIndex
. , day  X X(:) X(colon()) mwIndex k;
date rmfield(summer.field("date"), "day"). X(k)
C++ MATLAB. 10 X(1,1:10) X(1,colon(1,10)) mwIndex k(1,10);
, ,  1 X(k)
. , 2,4,6,8,10 X(2:2:10) X(colon(2,2,10)) mwIndex k(2,2,10);
: X X(k)
summer(3).field("image")(colon(),5) = empty();
.
summer(3).image(:,5) = []
, mwIndex, 
MATLAB.
. mwIndex ,
. 
4.3.4. colon(), mwIndex ,
. mwIndex all, colon().
. C++
. , 4.4.
,  MATLAB C++ 400 
. , 33  . 
1010 33 sqrt(). MATLAB. 
mwIndex i = ramp(4,6); , C++
mwArray A = sqrt(magic(10)(i,i));
MATLAB. 
C++  .
. ,
44, A B, (2,2) 
, x.
4.4.1. C++
mwArray A = rand(4), B = rand(4); 
double x = (A*B)(2,2); MATLAB. :
rand() , Y = cos(X);
: X Y mwArray.
290 4. 4.4. 291

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

. mwVarargout 4.4.1. MATLAB C++2


, .  ()
. ,  MATLAB C++ /
, mwVarargout.
L = tril(X, k); L = tril(X, k); 2
, m size, 1
[ A, B ] = eig(C); A = eig(&B, C); 1
. size() C++ mwVarargout  2
. size() C++  [ U, S, V ] = svd(X); U = svd(&S, &V, X); 1
MATLAB: 3
[x, y(2,3), z{:}] = size(m)
[ U, S, V ] = svd(X, 0); U = svd(&S, &V, X, 0); 2
3
C++: B = B = 7
size(mwVarargout(x, y(2,3), z.cell(colon())), m); cat(2,A1,A2,A3,A4,A5,A6); cat(2,A1,A2,A3,A4,A5,A6); 1
[d1,d2,d3,d4] = size(X); size( 1
, size() 
mwVarargout(d1, d2, d3, d4), 4
, varargout. "" varargout X);
. varargout 
, ,
<matlab>\extern\examples\cppmath (ex2.cpp)
mwVarargout, x.
. ,
varargout 
, mwVarargout.  svd() 
mwVarargout, .
varargout . MATLAB ++.
:
, 4.4.2.
C++ MATLAB;
,
, . C++ 
&  
; . varargin mwArray::cell 
, 
, . ,
mwVarargout, 
varargin :
. 32 ,
mwVarargout,  varargin_func(A, B, C.cell(colon(1,5)));
; A B , C , 
32 , mwVarargin, . cell()
32 , {1:5} : C.
mwVarargin,  C++ 
. varargin_func().
MATLAB C++ 
. . , 
varargin.
4.4.1. MATLAB C++2 varargin_func(C.cell(1,5), A, B);
MATLAB C++ / varargin_func(), 
A = eig(C); A = eig(C); 1 . C++
1 .
294 4. 4.4. 295

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

4.4.2. MATLAB C++


. : ()
mwArray function1(mwArray *out, mwArray x, mwArray y); C++#
mwArray function2(mwArray x); C = A <op> B MATLAB C++
DECLARE_FEVAL_TABLE C[i] = A[i]^B[i] .^ power()
FEVAL_ENTRY(function1)
FEVAL_ENTRY(function2)
END_FEVAL_TABLE C[i] = A[i]+B[i] + + plus()

myfunction() C[i] = A[i]-B[i] - - minus()
{

mwArray a = feval(&b, "function1", c, d);
mwArray f = feval("function2", g); * * mtimes()
}
C, , / / mrdivide()
, 
C*B = A
,  C, , \ mldivide()
, . A*C = B
3. fmins() , "func1" C = A*A*...*A ^ ^ mpower()
. fmins()  (
func1()  B )
, 0.25. ' ctranspose()

.' transpose()
4.4.4.
4.4.5.
MATLAB (+, -, *, /, ^) 
C++. ', \, .*, C
./, .\, .^, C++  C, libm, 
.  C C++, , 
C++. MATLAB C++.
 :
. ,  .
, C++ , .
C++. , , 
MATLAB.
4.4.2. MATLAB C++ .
C++# 
C = A <op> B MATLAB C++ (sin(), cos(), tan() . .), 
C[i] = A[i]*B[i] .* times() (log(), log10 () exp ()), ,
sqrt() abs(). ,
C[i] = A[i]/B[i] ./ rdivide() C++ int double, 
, mwArray.
C[i] = B[i]/A[i] .\ ldivide() , C++ sqrt(1),
sqrt(), 
298 4. 4.5. 299

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

MATLAB. MATLAB C++ 4.5.2. mwArray


. [ ] ( ) 
. { } ( ) [ 1.4 2.5 3.2 ] 1.4 2.5 3.2 1))3
.  [ 3.14e2 2.73e4; 314 27300 2))2.
. (;) . 1.73e3 1.41e2 ] 1730 141 )

.
, >> ,  [ 1+3i 2+7i ; 1+3i 2+7i
9-5i 8+4i ] 9)5i 8+4i 2))2
.
'kemerovo' Kemerovo 1))4
['kemerovo']
4.5.1. / mwArray [ 'Smolen'; Smolen 2))4
Polina] Polina
1.0e-7 * 0.00000001 0.00000002 2))2.
[ 0.1 0.2 ; 0.00000003 0.00000004 )
[] [ 1 2 ]
0.3 0.4 ]
{} {[1 2] 'smol'}
E 1e7
. 1.879
- -1.3e-8 .
+ 1+2i ASCII. .
i 1+2i data :
"abcd" [ 1 2 3 ; 4 5 6 ]
.fieldname , "file" 
; [ 1 2 ; 3 4 ] . data
*
file:
1e-10 * [ 1 2 ]
[ 1 2 ] file < data
/ .
: , , C++ ifstream 
, . ofstream . ,
,  , , A
mwArray, B. , 
.  , :
, #include <fstream.h>
. :
mwArray A = rand(4), B;
; . ofstream out_file("rand.txt", ios::out);
 out_file << A << ends;
out_file.close();
. .
, MATLAB 
ifstream in_file("rand.txt", ios::in);
C++. MATLAB  in_file >> B;
.
MATLAB C++ 
. , MATLAB 4.5.2. /
C++ : MATLAB C++ 
[ (1 + 2) 7; 4 5] C C++ / :
302 4. 4.5. 303

fprintf(), fscanf() , ASCII; fgetl() fgets() ASCII;


fgetl(), fgets() ; fopen()
fopen(), fclose() , . .
. // ex6.cpp
 ANSI
C ; , ,  #include <stdlib.h>
#include "matlab.hpp" // #1
. , fprintf()
MATLAB C++  int main(void)
.  {
. , ,  mwArray a("Alas, poor Yorick. I knew him, Horatio."); // #2
mwArray b("Blow, wind, and crack your cheeks!");
.
mwArray c("Cry havoc, and let slip the dogs of war!");
mwArray. mwArray d("Out, out, damned spot!");
fprintf() MATLAB C++  mwArray fid, r, a1, b1, c1, d1, mode("w"), sz, x, y;
, C++ fprintf(). mwArray file("ex6.txt");
, 
fid = fopen(file, mode); // #3
. fprintf(fid, "%s\n", a, b, c, d); // #4
fprintf() fscanf()  fclose(fid); // #5
.
1. / fid = fopen(file); // #6
a1 = fgetl(fid);
MATLAB C++ , C++, b1 = fgetl(fid);
, , c1 = fgetl(fid);
. fprintf(). d1 = fgetl(fid);
fprintf() : mwArray,  cout << a1 << endl << b1 << endl << c1 << endl << d1 << endl;
fclose(fid);
MATLAB C++,
, C++. : fid = fopen(file, mode);
mwArray file("foo.txt"), data=rand(4); fprintf(fid, "%f ", magic(4), rand(4)); // #7
int fd = fopen(file); fclose(fid);
fprintf(fd, "%f", data);
fid = fopen(file);
fprintf() C++, sz = horzcat(4,4);
, fprintf(), (int).  x = fscanf(fid, "%f ", sz); // #8
C++ fprintf() , , cout << x << endl;
y = fscanf(fid, "%f ", sz);
. , , 
cout << y << endl;
, , fclose(fid);
fprintf() mwArray.
sprintf() ( )  return(EXIT_SUCCESS);
MATLAB C++ }
mwArray. . .
2 (ex6.cpp). , 1. .
fopen(), fclose(), fprintf(), fgetl() fscanf().  MATLAB C++ matlab.hpp 
<matlab>\extern\examples\cppmath.  MATLAB C++.
: 2. , . 
fopen() mwArray ,
; mwArray.
fprintf() sprintf() MATLAB C++ 3. ex6.txt. C++ 
32 ; fopen(), fopen()
304 4. 4.5. 305

MATLAB C++ , mwArray 44. fscanf()


. .  , .
: ("r") :
("w"). .  'Alas, poor Yorick. I knew him, Horatio.'
fopen() 'Blow, wind, and crack your cheeks!'
mwArray. 'Cry havoc, and let slip the dogs of war!'
'Out, out, damned spot!'
, fopen() [
mwArray; C fopen(). 16 2 3 13 ;
4. . fprintf()  5 11 10 8 ;
C++ 30  9 7 6 12 ;
4 14 15 1
.  ]
. , ,
.  [
. 0.21896 0.93469 0.03457 0.00770 ;
0.04704 0.38350 0.05346 0.38342 ;
fprintf() MATLAB C++  0.67887 0.51942 0.52970 0.06684 ;
, C++ fprintf(). 0.67930 0.83096 0.67115 0.41749
, ]
. 2. . Glava_7 
, "%s".  7 Windows, 
, , fprintf() Borland C++ Builder, /
, a, b, c d. \n  fscanf() fprintf() MATLAB C++.
a, b, c d.
5. . C++ fclose() fclose() 4.5.3. MAT,
MATLAB C++ .
6. ex6.txt . MATLAB C++
fgetl() , load() save(), mwArray
. fgetl() MAT mwArray MAT.
, ,  MATLAB MAT, load() save()
PC. fgetl() ,  MATLAB , 
. MATLAB C++ C.
fgetl()  3. MATLAB C++ 
, . fgets(), ,  save() load() save()
. load() MATLAB. , save() load() 
7. magic(4) rand(4) .  MATLAB C++: 
"%f", fprintf() , mwArray mwArray*. 
, load() .
. fprintf()  MAT. save(), 
ASCII. mwArray . save():
8. . void save(const mwArray &file, const char* mode,
fscanf() ; const char* name1, const mwArray &var1,
. fprintf(),  const char* name2=NULL, const mwArray &var2=mwArray::DIN,
. .
.
. 12, .
[4, 4]. , fscanf()  const char* name16=NULL, const mwArray &var16=mwArray::DIN );
306 4. 4.6. mwArray 307

file MAT, mode ,  3 (ex7.cpp). ,


, . load() save() .
, ,  <matlab>\extern\examples\cppmath.
, mwArray, . // ex7.cpp
:
#include <stdlib.h>
mwArray, #include "matlab.hpp" //
. 32 ;
save() 16 ; int main(void)
,  {
try {
; mwArray x, y, z, a, b, c;
MAT .mat.  x = rand(4,4); //
, .mat y = magic(7);
z = eig(x);
;
,  // , "w"
. "w", ( save("ex5.mat", "x", x, "y", y, "z", z);
) "u", "w4" ,
// a, b, c
V4. save() mode, load("ex5.mat", "x", &a, "y", &b, "z", &c);
.
//
MAT, if (tobool(a == x) && tobool(b == y) && tobool(c == z))
ASCII. {
MAT. load(),  cout << "Success: all variables equal." << endl;
mwArray MAT. }
else
load(): {
void load( const mwArray &file, cout << "Failure: loaded values not equal to
const char* name1, mwArray *var1, saved values." << endl;
const char* name2=NULL, mwArray *var2=NULL, }
. }
. catch (mwException &ex) {
. cout << ex << endl;
const char* name16=NULL, mwArray *var16=NULL ); }
return(EXIT_SUCCESS);
file MAT. ,  }
, , , 
, mwArray, .
: 4.6. mwArray
mwArray; mwArray. 
load() 16 mwArray; mwArray , 
,  , new delete,
MAT; , ,
.
mwArray. load() , mwArray 
; . , , 
, . . , C++ 400 
.mat,  . mwArray,
; . 
MAT, ASCII MAT. , , , .
308 4. 4.6. mwArray 309

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

. 4.3 , . friend inline istream& operator>>(istream &is, mwArray&).


.  , ( ) mwArray
: mwArray, mwSubArray mwIndex. mwArray . C++, 
operator() mwSubArray. mwSubArray "" , . Read(),
, . .
() ,  , >> << MAT
, mwArray, , . Read() Write(),
. mwArray.
mwArray (),  1. Write() ,
n . . Read() . , Write(), Read(). 
operator()  . Read()
32 . ( const)  , .
,  MAT .
. void Read(istream&). mwArray . 
mwArray operator()(const mwVarargin &a) const; , *, 
mwSubArray operator()(const mwVarargin &a);
[, , ,
operator()  , ].
. ,  void Write(ostream&, int32 precision =5, int32 line_width =75) const. 
. mwArray ( )
mwArray operator()(const mwArray &a1, const mwArray &a2) const; . <<() 
mwSubArray operator()(const mwArray &a1, const mwArray &a2);
, , 80 
. cell()  .
. , A.cell(1,2)  mwArray &operator=(const mwArray&). . C++ 
A. , . ,
. field() ,
. , A.field("name")  ; , 
name A. ( const) , . A = B
,  B, A .
.
mwArray field(const char *fieldname) const; //( )
mwSubArray field(const char *fieldname); //( ) 4.6.4.
MATLAB size() . 
4.6.3. MATLAB C++
size(), . C++ 
mwArray. , << >>,  , .
.  mwArray Size .
, . ( ) :
friend inline ostream& operator<<(ostream &os, const mwArray&). ( ) . 
mwArray . Size() ,
cout, mwArray  .
,  int32 Size() const. .
. Write(), int32 Size(int32 dim) const. ( ) 
. .
312 4. 4.6. mwArray 313

int32 Size(int32* dims, int maxdims=2) const.  SetData() , 


, dims.  mwArray, , 
maxdims , . ,
. dims  mwArray , GetData() mwArray:
maxdims . maxdims  mwArray A = rand(4), B = magic(10);
mxArray,  B.SetData(A.GetData()); // .
. 3. , ,
. SetData(). mwArray
, , .
mwArray Size size. ExtractScalar() ExtractData(). ExtractScalar() Extract
int32 dims[2]; Data() ,
mwArray mat = rand(4,4); mwArray. ExtractScalar() 
mwArray sz;
.
// Size. 8 ExtractData() C++
// , 4 4. . .
mat.Size(dims); A 1111 
// size. . ExtractScalar()
// 85 , , cdata ( 
// : 10 ) , .
// ( ).
mwArray A = magic(11) + (rand(11) * i());
sz = size(mat);
double rdata, cdata;
rdata = A.ExtractScalar(9); // 9-
4.6.5. mwArray rdata = A.ExtractScalar(cdata, 17); //
// 17- , cdata
C++ , 
int32 *integers = new int32[ 11 * 11 ]; // 121
mwArray A.ExtractData(integers); //
. mwArray. .
4.3. double *real_data = new double [ 11 * 11 ]; // 121
GetData(). double *complex_data = new double [ 11 * 11 ];
// real_data
GetData(), . A.ExtractData(real_data);
mxArray *.  //
. A.ExtractData(real_data, complex_data);
, C++ ExtractScalar() MN 1(M*N). 
, mxArray *, mxGetPr() ( , A.ExtractScalar(9) 9 .
) mxGetPi() (  ExtractScalar() , 
). GetData (): N (N+1).
mwArray A = magic(17); ToString(). mwArray,
double *real_data = mxGetPr(A.GetData()); mwArray ToString(). :
2. , mwArray A = "MATLAB";
GetData (), mxGetPr () mxGetPi (). mwString s = A.ToString();
,  char *c = strdup((char *)s);
, mwArray.  mwString
. , , mwString 
SetData( ). GetData() SetData(),  . mwString , 
, mwArray. char *.
314 4.
ToString() char* 
, strcat(str, A.ToString()).
mwString,
strdup(), . , 
.
4. mwString char* . 5. MATLAB 3.0
, mwString .
. 3.0 MATLAB 6.5 (R13).
. ,
3.0 MATLAB 
MATLAB. MATLAB
m MATLAB : MEX, C C++
, , ,
C S Simulink, Excel COM
.
MATLAB 
. 
C C++ .

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

5.1.1. ApplicationData\MathWorks\MATLAB\R13 ( User


Profile Directory ,
MATLAB , , ). 
. 3 MATLAB , MATLAB C C++
MATLAB 6.5. MATLAB C MEX. ,
ANSI C C++.  C C++, mex
. , . C MEX 
MATLAB. , MATLAB ANSI C :
(Lcc), MATLAB. mex filename.c
, MATLAB  , C C++, 
C++, MEX C++. mex .
MATLAB . C
: C++ 
MATLAB; setup. ,
ANSI C C++; mex -setup
MATLAB MEX 
MATLAB DOS , 
MATLAB DOS UNIX.
. setup 
C MEX, C/C++  .
(DLLs) MATLAB , 
C/ . mex
C++ : .
C MATLAB Lcc ( C++); C C++, f:
Watcom C/C ++ 10.6 11.0; mex -f <file> ...
Borland C++ 5.3, 5.4, 5.5, 5.6 (Borland C++ Builder 3.0, 4.0, 5.0 6.0);
-f mex <file> 
Microsoft Visual C/C ++ (MSVC) 5.0, 6.0 7.0.
mex. <file> ,
MathWorks (addin) MATLAB  <file> .
Visual Studio, MathWorks C/C++.
Microsoft Visual C/C++ (MSVC), MEX. 
MATLAB Visual Studio MATLAB  . 5.1.1 
, mex -setup Microsoft Visual C/C++ MATLAB.
5 6. , addin MATLAB Visual Studio
Microsoft Visual C/C ++ 7.0. 5.1.1. 3
.

:
Lcc C, 2.4 ( MATLAB) lccopts.bat
mex.bat MEX; Microsoft Visual C/C++, Version 5.0 msvc50opts.bat
mcc.exe MATLAB m C/ Microsoft Visual C/C++, Version 6.0 msvc60opts.bat
C++ ; Microsoft Visual C/C++, Version 7.0 msvc70opts.bat
mbuild.bat ,  Watcom C/C++, Version 10.6 watcopts.bat ( mex,
MATLAB C/C++,  Watcom C/C++, Version 11.0 ?mbuild)
. wat11copts.bat (
mex, ?mbuild)
Borland C++ Builder 3 bcc53opts.bat
mex.bat mbuild.bat . Borland C++ Builder 4 bcc54opts.bat
. mex mbuild  Borland C++ Builder 5 bcc55opts.bat
, mexopts.bat compopts.bat, Borland C++ Builder 6 bcc56opts.bat
318 5. MATLAB 3.0 5.1. MATLAB 319

. 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

x = [007 06 10]; startPoint = floor((corners(theRand(i),:)+startPoint)/2);


theImage(startPoint(1),startPoint(2)) = 1;
Borland m,
end

, 
x = [7 6 10];
(Iterated Function System algorithm).
, , 
5.1.5. , , 
MATLAB MEX . .
m . , ,
, mex mbuild .
MATLAB . .
: , 
()  50 000.
 m, mcc 
, . 
MATLAB.
, ;
mcc -x gasket

,  mcc :
. , ; gasket.c C ;
. ,  gasket.h ;
, . gasket_mex.c  ();
. gasket.dll .
MATLAB  mcc mex
m gasket.m <matlab>\extern\ gasket.dll gasket.c gasket_mex.c.
examples\compiler\. . MEX MATLAB 
, m:
. ,  x = gasket(50000);
,  MATLAB mex (gasket.dll), m
. (gasket.m). m MEX
, m gasket.m: (gasket) ,  . 
function theImage = gasket(numPoints) MATLAB:
%GASKET An image of a Sierpinski Gasket. imagesc(x); colormap([1 1 1;0 0 0]);
% IM = GASKET(NUMPOINTS) axis equal tight
% Example:
% x = gasket(50000);
. 5.1.3 ,
% imagesc(x);colormap([1 1 1;0 0 0]); 50 000 .
% axis equal tight
%
%
Copyright (c) 1984-98 by The MathWorks, Inc
$ Revision: 1.1 $ $Date: 2002/06/20 22:18:14 $
5.2. mbuild

theImage = zeros(1000,1000);

corners = [866 1;1 500;866 1000];
startPoint = [866 1]; .
theRand = rand(numPoints,1); MathWorks mbuild,
theRand = ceil(theRand*3);
. 5.1.3. .
for i=1:numPoints 50 000 mbuild 
326 5. MATLAB 3.0 5.2. mbuild 327

 5.2.1. mbuild Microsoft Windows


. mbuild:
mbuild [option1 ... optionN] sourcefile1 [... sourcefileN] @filename @filename mbuild
[objectfile1 ... objectfileN] [libraryfile1 ... libraryfileN] filename,
[exportfile1 ... exportfileN]

. () , )c , .
MATLAB C/C++,  ,
. mbuild bat )D<name> [#<def>] C/C++
, ,  <name>. #define <name>
C/C++
. 5.2.1 mbuild )D<name>#<value> C/C++.
Microsoft Windows. #define <name> <value>
: .c, .cpp, .idl, .rc. C/C++ .
C/C++ )f <file> <file>
C/C++. C/C++ . <file> ,
mbuild .
, , C )g .

DOS MATLAB

mbuild filename.c )h[elp] Help; mbuild
, C, mbuild )I<pathname> <pathname> ,
.
. C <name>#<value>
<name>. <value> ,
, ,
mbuild -setup
CFLAGS ='opt1 opt2'. <value>,
setup mbuild ,
. compopts.bat  . ,
. $, ,
C. mbuild CFLAGS = "$CFLAGS opt2".
)inline (mx*).
:
)lang <language> . <language>
; c cpp. , mbuild ,
(User Profiles); (C C++) ,
<matlab>\bin. .
. ,
mbuild .

, mbuild C < language > =c C cpp ) C++
. mbuild , C C++ )n . ,
: .c C .cpp, .cxx, .cc C++. mbuild ,
, mbuild
, v: )nohg MATLAB C/C++
mbuild-v filename1 [filename2 ...] (Handle Graphics)
)O
mbuild ,  )outdir <dirname> , ,
. mbuild <dirname>.
Microsoft Windows. UNIX . MATLAB output, output
Compiler.
328 5. MATLAB 3.0 5.3. mcc 329

5.2.1. mbuild Microsoft Windows () Simulink S. ,


mymfile.m, C Simulink S 
:
)output <name> <>.
( mcc -S mymfile
.) C. ,
)regsvr regsvr32 , mymfile.m, C ,
MATLAB, :
.
mcc -m mymfile
, COM .
)setup C++. , 
, mymfile.m, C++ , 
mbuild MATLAB, :
)U<name> C mcc -p mymfile
<name> ( )D)
)v ; C . 
, mymfile.m, Handle Graphics, C
, , , MATLAB, 
. :
, , mcc -B sgl mymfile
, .
C++ .

, mymfile.m, Handle
Graphics, C++ ,
. (-f, -g -v) 
MATLAB, :
mcc mbuild. 
mcc -B sglcpp mymfile
, -M mcc.
-M . mcc. C. C libmymfile.dll m
mymfile.m :
5.3. mcc mcc -m -W lib:libmymfile -T link:lib mymfile.m
C++. C++
mcc. , m mymfile.m :
MATLAB 
mcc -p -W lib:libmymfile -T compile:lib mymfile.m
. 
. , C . C
.  ,
, , :
. . mcc -W lib:mylib -L C -t -T link:lib -h Function1 Function2 ...
MATLAB (P). , 
5.3.1. mymfile.m, MATLAB (P) :
mcc -B pcode mymfile
, MATLAB
1. -g 
. , ,
.
mex mbuild
MATLAB .
MEX. , mymfile.m, C 5.3.2. mcc
C MEX,  mcc. 
MATLAB, : . , . 5.3.1
mcc -x mymfile .
330 5. MATLAB 3.0 5.3. mcc 331

5.3.1. mcc 5.3.1. mcc ()


/ /
A annotation: / type = all m C
type ) comments -W main -L C -t -T
C/C ++ none link:exe
A debugline: setting = on -h libmmfile.mlib
setting off M string mex
mbuild

A line: setting = on
setting #line off o outputfile /
C/C ++
b Visual Basic,
Excel Formula O option:[on|off] option =
Function array_indexing
COM O all fold_mxarrays
B filename )B filename O none fold_non_scalar_
O list mxarrays
mcc
ld_scalar_mxarrays
filename
optimize_conditionals

optimize_integer_
mcc. for_loops
c , percolate_simple_types
C, T, speculate
p C++
-T codegen -W main -L Cpp -t -T
d directory link:exe
-h libmmfile.mlib
f filename S
filename mex setup Simulink S) -W simulink -L C -t -
mbuild -setup T link:mex
F option option = list libmatlbmx.mlib
expression- t ) C/C++
indent:n
page-width:n T target target = codegen
statement- compile:bin
indent:n link:bin
g bin =mex, exe, lib
-G -A debugline: u number
on -O none Simulink S)
G . v .

.
w option option = list, level,
h
level:string
i level =disable
m), enable, error
. w
I directory )
I , (default)
-A debugline: W type type = mex
on main
L language language = C simulink
Cpp lib:string
332 5. MATLAB 3.0 5.3. mcc 333

5.3.1. mcc () mcc ,


/ , . ,
type = com:compnm mcc -m -W none test.m
[,clnm[,mj.mn]] :
comhg:compnm mcc -t -W main -L C -T link:exe -h -W none test.m
[,clnm[,mj.mn]]
excel:compnm W. , 
[,clnm[,mj.mn]] , , W none, 
excelhg:compnm .
[,clnm[,mj.mn]] . MATLAB
x 
MEX) -W mex -L C -t T
. 
link:mexlibrary
ibmatlbmx.mlib , , 
y number . .
Simulink S) <matlab>/toolbox/compiler/bundles.
Y licensefile licensefile 5.3.2 
.
z path

5.3.2.
?


5.3.3. mcc )m macro_option_m )t )W main )L C )T link:exe h
C libmmfile.mlib
mcc : )p macro_option_p )t )W main )L Cpp )T link:exe h
mcc [-options] mfile1 [mfile2 ... mfileN] C++ libmmfile.mlib
[C/C++file1 ... C/C++fileN] )x macro_option_x mex) )t )W mex )L C )T
. mcc MATLAB. mcc  link:mexlibrary libmatlbmx.mlib
MATLAB ( MATLAB),  )S macro_option_S Simulink S) )t )W simulink )L C )T
DOS UNIX ( ). link:mex libmatlbmx.mlib
)g macro_option_g )G )A debugline:on )O none
MATLAB mcc.
 . ,
. m,
:
C. m 
mcc -m -g myfun
:
(), : -t -W main -L C -T link:exe -h libmmfile.mlib
mcc -mg myfun
:
, ,  -t m C/C++;
, . , : -W main ( main);
mcc -m -A full myfun % , -L C C ;
mcc -mA full myfun % , A
-T link:exe , link:exe 
: ;
mcc -Am full myfun % , A -h 
mcc  C C++ , m;
, mex mbuild, libmmfile.mlib 
C C++. , .
334 5. MATLAB 3.0 5.3. mcc 335

, -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, , main POSIX main();


C/C++, #line simulink Simulink C MEX S;
: lib:<string> , 
mcc -A annotation:all -A line:on ... 
F <option> (). .
. <option>: , 
list ; m. <string> 
expressionindent:n n, C/C++ . .exports, 
4; ;
pagewidth:n  none . none.
n, 80; 3. , 
statementindent:n n, m . ,
2. , .
l ( ). C/C++ , , 
.  .
, 
. 5.3.5.
mcc -A debugline:on ...

L <language> ( ). .
C Cpp. C.  b ( Visual Basic). Visual Basic (.bas),
, . Microsoft Excel Formula Function COM
O <option> ( ). m . Visual Basic 
, C/C++ , MATLAB
m MATLAB. : .
B <filename>: [<a1>, <a2>...,] ( 
-O list ;
). -B <filename>:[<a1>,<a2>...,] mcc
-O all , .
B opt_bundle_all; . 
-O none . B opt_bundle_none; mcc / .
-O <opt option>:[on|off] B.
, <opt option> : ,
array_indexing; . ,
fold_mxarrays; <matlab>\toolbox\compiler\bundles\csharedlib C 
fold_non_scalar_mxarrays; ,
fold_scalar_mxarrays; -t -W lib:%1% -T link:lib -h libmmfile.mlib
optimize_conditionals; C , ,
optimize_integer_for_loops; :
percolate_simple_types; mcc -B csharedlib:mysharedlib <f1>,<f2>,...
speculate. %n% 
W <type> ( ). . , , %1% mysharedlib.
m. -B
, UNIX, DOS. -B MATLAB,
. : , -B, . :
mex mexFunction(); mcc -B csharedlib:libtimefun weekday data tic calendar toc
338 5. MATLAB 3.0 5.3. mcc 339

c ( C). C, MEX link:exe , compile:exe,


. -T codegen,  ;
mcc. link:lib , compile:lib,
d <directory> ( ).  (DLL).
, d. 4. mex mexlibrary <target>
h ( ). . mex, MEX, exe mbuild, 
mex , lib mbuild 
-m .
, -m -h.  v (). , :
h m ;
mcc. , ;
I <directory> ( ). , ;
. -I mex mbuild.
. :
-v -v mex mbuild
-I <directory1> -I <directory2>
mex mbuild.
, m w (). . 
directory1, directory2.  -w:
, MATLAB. -w ,
o <outputfile>. ( )  ;
( ).  -w list ,
. <string> enable, disable error;
t ( m C/C++). m,  -w ;
, C/C++. -w disable[:<string>] , 
T <target> ( ). .  <string>. :<string> disable 
target: ;
codegen m C/C++  -w enable[:<string>] , 
. codegen; <string>. :<string> enable 
compile:mex , codegen, ;
C/C++ , MEX -w error[:<string>] , 
Simulink S; <string>, . :<string>
compile:mexlibrary , codegen,  error .
C/C++ , 
MEX;
compile:exe , codegen, 5.3.6. mbuild/mex
C/C++ ,  f <filename> ( ). 
; mex mbuild. 
compile:lib , codegen, MATLAB. 
C/C++ ,  mex -setup mbuild setup
(DLL); .
link:mex , compile:mex, G ( ). mex mbuild C/C++
MEX Simulink S; . -G,
link:mexlibrary , compile:mexlibrary, MEX .
MEX ( Simulink M "string" ( ). string
S); mex mbuild.
340 5. MATLAB 3.0 5.4. 341

, -M "-Dmacro=value". -M  , MATLAB m


; -M.  ,
z <path> ( ). , m hello.m.
. <matlab>/extern/examples/compiler. 
, MATLAB MATLAB:
matlabroot. mcc -m hello.m

5.4. hello.exe. MSDOS,
: Hello, World.

, 5.4.1.
MATLAB . 
MATLAB , 
MATLAB . m
MEX. m 
MATLAB. 
MATLAB. , 
MEX , 
m ,
C/C++ , 
.
, .
, , 
. C/++
mymfile.m, C , 
MATLAB, MATLAB, C/++
MATLAB, :
MATLAB C/C++.
mcc -m mymfile
C/++ m,
m, MEX , mymfile.m, C++ 
C C++. MATLAB m  , MATLAB, :
C/++. /C++,  mcc -p mymfile
,
MATLAB C/C++. m, mrank.m main.m ( 
Windows UNIX  <matlab> \extern\examples\compiler\).
C C++ , mbuild  C ( C++ ).
MATLAB mrank.m r
. , r(3)
MathWorks  33. , r = zeros(n, 1)
bat mbuild. C C++ , .
, mbuild setup.  function r = mrank(n)
setup r = zeros(n,1);
for k = 1:n
. r(k) = rank(magic(k));
, mbuild ,  end
ex1.exe . main.m "main",
C ex1.c <matlab>/extern/examples/cmath. mrank :
mbuild MATLAB function main
mbuild ex1.c r = mrank(5)
ex1.exe 32 Windows  ,
. ex1.exe DOS  , MATLAB:
. mcc -mc main mrank
342 5. MATLAB 3.0 5.4. 343

-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

* Windows C main program illustrating the use of the PkgInitialize(); /* M- */


* MATLAB Math Library. /* */
* Calls mlfMrank, obtained by using MCC to compile mrank.m. mlfSetPrintHandler(WinPrint);
* $Revision: 1.3 $
*/ /*
*/
#include <stdio.h> argv[argc] = "mrank.exe";
#include <math.h> argv[++argc] = strtok(lpszCmdLine, " ");
#include "matlab.h" while (argv[argc] != NULL) argv[++argc] = strtok(NULL, " ");
#include <windows.h> if (argc >= 2) {
n = atoi(argv[1]);
/* mlfMrank */ } else {
extern mxArray * mlfMrank( mxArray * ); n = 12;
}
static int totalcnt = 0;
static int upperlim = 0; /* mxArray 1--1 n */
static int firsttime = 1; N = mxCreateDoubleMatrix(1, 1, mxREAL);
char *OutputBuffer; *mxGetPr(N) = n;

void WinPrint( char *text ) /* mlfMrank, mrank.m */


{ R = mlfMrank(N);
int cnt;
if (firsttime) { /* ( Windows-) */
OutputBuffer = (char *)mxCalloc(1028, 1); mlfPrintMatrix(R);
upperlim += 1028; WinFlush();
firsttime = 0;
} /* */
cnt = strlen(text); mxDestroyArray(N);
if (totalcnt + cnt >= upperlim) { mxDestroyArray(R);
char *TmpOut;
TmpOut = (char *)mxCalloc(upperlim + 1028, 1); PkgTerminate(); /* M- */
memcpy(TmpOut, OutputBuffer, upperlim);
upperlim += 1028; return(0);
mxFree(OutputBuffer); }
OutputBuffer = TmpOut;
}
mrankwin.c mlfMrank. ,
strncat(OutputBuffer, text, cnt);
} , ,
mlfMrank. , , 
void WinFlush(void) , mlfMrank .
{ MessageBox(NULL, OutputBuffer, "MRANK", MB_OK);
, 
mxFree(OutputBuffer); }
:
PkgInitialize();/* m- */
WINAPI
WinMain( HANDLE hInstance, HANDLE hPrevInstance, LPSTR lpszCmdLine, int

nCmdShow ) extern mxArray * mlfMrank( mxArray * );
{
mlfMrank .
#define MAXCMDTOKENS 128
mxArray.
LPSTR argv[MAXCMDTOKENS]; mxArray * C 
int argc = 0; MATLAB C/C++. ,
mxArray *N; /* n. */
mxArray * N 11 , mrankwin
mxArray *R; /* . */ mxCreateDoubleMatrix:
int n; /* . */ N = mxCreateDoubleMatrix(1, 1, mxREAL);
346 5. MATLAB 3.0 5.4. 347

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

mlfFunc1 mlfAssign(&zmx, mlfFunc2(xmx)); //


mlxFunc1 zc = *mxGetPr(zmx); //
mlfFunc2
mlxFunc2 Edit2->Text = FloatToStr(yc); //
_mlfFunc1 Edit3->Text = FloatToStr(zc); //
_mlxFunc1 mylibTerminate();
_mlfFunc2 }
_mlxFunc2
_mylibInitialize
1. mcc
_mylibTerminate mlib, . :
Unit1.cpp. mcc -m timer /pathname/libtimefun.mlib
Glava_5\ Pr_5_04_3_C_Sh_Lib_BB  :
CD. (UNIX) lib;
(PC UNIX) ;
// Unit1.cpp (PC UNIX) mlib
;
#include <vcl.h> (PC UNIX)
#pragma hdrstop . mlib
#include "matlab.h" // MATLAB
,
#include "mylib.h" // mylib.h
#include <windows.h> .
#include "Unit1.h" C++. (,
#pragma package(smart_init)
Lcc )
#pragma resource "*.dfm" mcc -B csharedlib:libfunc1 -L cpp -T compile:lib func1.m.
TForm1 *Form1; : libfunc1.cpp, libfunc1.hpp libfunc1.obj 
//-
__fastcall TForm1::TForm1(TComponent* Owner) func1.m. libfunc1.cpp C++
: TForm(Owner) . m
{ . libfunc1.cpp ,
}
, ,
double xc;
C++, . libfunc1.hpp
void __fastcall TForm1::Edit1Change(TObject *Sender) , m.
{
xc = StrToFloat(Edit1->Text);// x
} mcc -W lib:libfunc1 -L cpp -t -T link:lib -h func1
libfunc1.dll, libfunc1.cpp libfunc1.hpp.
//- ++ Pr_5_04_4_Cpp_Lib
void __fastcall TForm1::Button1Click(TObject *Sender) Pr_5_04_5_Cpp_Sh_Lib_Code CD.
{ , , Microsoft Windows NT, 
mylibInitialize(); C++ .
mxArray *xmx; // mxArray . MathWorks
mxArray *ymx; // mxArray
mxArray *zmx; // mxArray (addin) MATLAB
double yc; // Visual Studio,
double zc; // Microsoft Visual C/C++ (MSVC). MATLAB Visual Studio 
m MSVC. 
xmx = mclInitializeDouble(xc); // x mxArray m Visual C++.
MATLAB MATLAB C/
mlfAssign(&ymx, mlfFunc1(xmx)); // C++. , MATLAB Visual Studio
yc = *mxGetPr(ymx); // double mxArray Microsoft Visual C/C ++ 7.0.
352 5. MATLAB 3.0 5.5. 353

Visual Studio <MATLAB>\bin\win32.


mbuild -setup, mex setup,  ,
Microsoft Visual C/C++ 5 6.  . Windows 
MATLAB Visual Studio . [8], <LIBRARY>\bin\win32, <LIBRARY> 
MATLABAddin.hlp <matlab>\bin\win32, , 
Help MATLAB Visual Studio. MATLAB.

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

y=sin(pi*x^2)*exp(1)^(3*x); if (nlhs > 1) {


fprintf(1,Ans = %1.4f,y); mlfError(
mxCreateString(
x, y "Run-time Error: File: func Line: 1 Column: 1
. . The function \"func\"" " was called with more than
: the declared number of outputs (1)."), NULL);
mcc -m O none func }
if (nrhs > 1) {
func.c, func.h, func.exe mlfError(
func_main.c ( Glava_5\Pr_5_05_1_C_Appl mxCreateString(
"Run-time Error: File: func Line: 1 Column: 1
CD). func_main.c .
The function \"func" "\" was called with more than
func.c  .  the declared number of inputs (1)."), NULL);
, MATLAB, }
. : for (i = 0; i < 1; ++i) {
mplhs[i] = NULL;
#include "func.h" }
#include "mwservices.h" for (i = 0; i < 1 && i < nrhs; ++i) {
#include "libmatlbm.h" mprhs[i] = prhs[i];
}
void InitializeModule_func(void) {} for (; i < 1; ++i) {
mprhs[i] = NULL;
void TerminateModule_func(void) {} }
mlfEnterNewContext(0, 1, mprhs[0]);
static mxArray * Mfunc(int nargout_, mxArray * x); mplhs[0] = Mfunc(nlhs, mprhs[0]);
mlfRestorePreviousContext(0, 1, mprhs[0]);
_mexLocalFunctionTable _local_function_table_func plhs[0] = mplhs[0];
= { 0, (mexFunctionTableEntry *)NULL }; }
/* /*
* The function "mlfFunc" contains the normal interface for the "func" * The function "Mfunc" is the implementation version of the "func"
* M-function from file "d:\appl_ml\5_compiler_30\pr_5_05_1_c\func.m" * M-function from file "d:\appl_ml\5_compiler_30\pr_5_05_1_c\func.m"
* lines 1-5). This function processes any input arguments and passes * (lines 1-5). It contains the actual compiled code for that
* them to the * M-function. It is a static function and must only be called from
* implementation version of the function, appearing above. * one of the interface functions, appearing below.
*/ */
mxArray * mlfFunc(mxArray * x) { /*
int nargout = 1; * function y = func(x)
mxArray * y = NULL; */
mlfEnterNewContext(0, 1, x); static mxArray * Mfunc(int nargout_, mxArray * x) {
y = Mfunc(nargout, x); mexLocalFunctionTable save_local_function_table_
mlfRestorePreviousContext(0, 1, x);
= mclSetCurrentLocalFunctionTable(&_local_function_table_func);
return mlfReturnValue(y);
mxArray * y = NULL;
}
mxArray * ans = NULL;
mclCopyArray(&x);
/*
/*
* The function "mlxFunc" contains the feval interface for the "func"
* x=input('x= ')
* M-function from file "d:\appl_ml\5_compiler_30\pr_5_05_1_c\func.m"
* (lines 1-5). The feval function calls the implementation version */
* of func through this function. This function processes any input mlfAssign(&x, mlfInput(mxCreateString("x= "), NULL));
* arguments and passes them mclPrintArray(mclVa(x, "x"), "x");
* to the implementation version of the function, appearing above. /*
*/ * y=sin(pi*x^2)*exp(1)^(3*x);
void mlxFunc(int nlhs, mxArray * plhs[], int nrhs, mxArray * prhs[]) { */
mxArray * mprhs[1]; mlfAssign(&y, mclMtimes(mlfSin(mclMtimes(
mxArray * mplhs[1]; mlfScalar(3.141592653589793),
int i; mclMpower(mclVa(x, "x"), mlfScalar(2)))),
356 5. MATLAB 3.0 5.5. 357

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

static mwArray Mfunc(int nargout_, mwArray x) { , , 


mwLocalFunctionTable save_local_function_table_ m, .
= &_local_function_table_func;
mwArray y = mwArray::UNDEFINED; , 
mwArray ans = mwArray::UNDEFINED; .
// .
// x=input('x= ') .
//
x = input(mwArray("x= ")); -t. :
mwVa(x, "x").Print("x"); mcc -W main -h file.m
//
// y=sin(pi*x^2)*exp(1)^(3*x);
file.m m, file.m,
// file_main.c. -t
y = sin(3.141592653589793 * (mwVa(x, "x") ^ 2)) mcc -W main -h -t file.m
* (svDoubleScalarExp(1.0) ^ 3 * mwVa(x, "x"));
// file_main.c, file.c m, file.m.
// fprintf(1,Ans = %1.4f,y); MEX. -W mex -L C MEX,
// mexFunction, MATLAB.
ans.EqAns(Nfprintf(0, 1, mwVarargin("Ans = %1.4f", mwVv(y, "y"))));
mwValidateOutput(y, 1, nargout_, "y", "func");

return y; feval MEX 
} m,
NF . , . MATLAB.
m nargout. nargout -x  ,
int . , , 
nargout, , , MATLAB. h, ,
NULL  MEX.
. (Main) . C C++, 
VF . C C++ .
, m nargout POSIX main POSIX shell 
. . "
" m (main) POSIX.
POSIX (main) . POSIX main()
5.5.3. ,  MATLAB.

,  command argument
, 
. , command('argument')
C/C++
, MATLAB, 
mex, . 
POSIX ,
:
DOS/UNIX ,
/ ;
MATLAB.
feval feval
1. POSIX Portable Operating System Interface for computer
;
environments, (
; IEEE, ).
,  C.
. : C , C , 
,  *.mlib. , :
MATLAB. mylib.c  ;
362 5. MATLAB 3.0 5.5. 363

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);

function y = mmult(a,b) collect_one


y = a*b; C, , ,
MEX . 
mcc -x tmmult %#external.
366 5. MATLAB 3.0 5.5. 367

%#external MATLAB, measure_from_device().


#include "matlab.h"
(f) m. 
#include "collect_external.h"
, . #include <math.h>
m (, ,
). extern double measure_from_device(void);
file_external.h mxArray * Mcollect_collect_one(int nargout_);
file_external.hpp, file m, {
%#external.  return( mlfScalar( measure_from_device() ));
extern, . }
double measure_from_device(void)
{
. static double t = 0.0;
c cpp t = t + 0.05;
return sin(t);
m. feval, }
m, m
,
. .
. C
, 
mcc -mc collect.m
%#external, , file_external.h
file_external.hpp. C C++  collect.m MEX
, mcc -x collect.m measure.c
. feval. C C++
%#function <function_name-list>
collect_one: MATLAB, ()
function collect feval MATLAB, 
feval eval 
y = zeros(1, 100); % pre-allocate the matrix
for i = 1:100 . -h
y(i) = collect_one; m, 
end .
function y = collect_one
%#function 
, m, m
%#external , ,
persistent t; %#function. :
if (isempty(t))
t = 0; %#function myfunctionwritteninc
end , myfunctionwritteninc m,
t = t + 0.05; feval. ,
end
y = sin(t); .
M. m

, mex , , mex
collect_external.h,
m. , 
. 
m, %#mex, 

MEX. :
extern mxArray * Mcollect_collect_one(int nargout_);
function y = gamma(x)
. %#mex
C measure.c, error(gamma MEX-file is missing);
368 5. MATLAB 3.0 5.5. 369

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

Borland C++. m  6.1.1. ()


, 8
9 , Borland
bcc54compp.bat Borland C++ Builder 4
: bcc55compp.bat Borland C++ Builder 5
Error <file>.c <line>: Illegal octal digit in function bcc56compp.bat Borland C++ Builder 6
<functionname>
, Borland 009.0  , MATLAB Linux,
mbuildopts.sh.
. 
(07), . , , .
mbuild -setup
x = [007 06 10]; , 
Borland, , .
user profile .
x = [7 6 10];
. C C++ 6.1.2. MATLAB 4
MATLAB. MATLAB
mbuild, C++ C. 

, setup mbuild  4 
. mbuild  MATLAB:
: 4 MATLAB 
/ ; (MATLAB Component Runtime, MCR)
. MATLAB C/C++. MCR 
MATLAB (mcc) mbuild
. , mcc-m mcc -l mbuild (shared libraries), m
. , MATLAB;
, C C++ 4 (),
, .  m;
C/C++. 4 , , ,
MATLAB .
. C C++. C,
mbuild -setup . 
. MATLAB ;
, MATLAB 4 , 
Windows, . . 4 
;
6.1.1. 4
(bundle files);

4 mglinstaller 
lcccompp.bat Lcc C, Version 2.4 (included with MATLAB)
. MCRInstaller;
msvc60compp.bat Microsoft Visual C/C++, Version 6.0
msvc70compp.bat Microsoft Visual C/C++, Version 7.0 4 -B sgl -B sglcpp 
msvc71compp.bat Microsoft Visual C/C++, Version 7.1 . 
bcc53compp.bat Borland C++ Builder 3 ;
376 6. MATLAB 4 6.1. 377

4 MATLAB Addin Visual Studio; ,


4 . . ,
, .
MATLAB. . 4 MATLAB
, MATLAB JIT; , .
4 MEX S , ,
Simulink m, MATLAB 7 .
. MATLAB JIT (. 6.1.2).
m p 
; 6.1.2.
4 : mbchar,
mbcharscalar, mbcharvector, mbint, mbintscalar, mbintvector, mbreal, mbreals
A
calar, mbrealvector, mbscalar mbvector ; B pcode P)
MATLAB  F
mccsavepath,  H
DOS UNIX. I m)
, mccsavepath  L / (
4; )
MATLAB ,  L /++
MATLAB loadlibrary. O
P C++ ( ,
. , , )
MATLAB  S S) Simulink
, . 4 T ) C/C ++
(),  U S) Simulink
m. , X MEX)
Release 14 Compiler C C++: Y S) Simulink
4 
MATLAB C/C++, mlf ,  . 
, ; (. 6.1.3).
initialize ,
, , T 6.1.3.
. /
. mlf, B csglcom B ccom
m, B csglexcel B cexcel
B csglsharedlib B csharedlib
.
B cppsglcom B cppcom
. (void). 
B cppsglexcel B cppexcel
mlf .  W comhg W com
: W excelhg W excel
void mlf<function-name>(<list_of_input_variables>); W libhg W lib
 : W mainhg W main
void mlf<function-name>(int number_of_return_values,
<list_of_pointer_to_return_variables>, 4. . 6.1.4
<list_of_input_variables>); . .
378 6. MATLAB 4 6.2. 379

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

foo.ctf CTF. 6.2.1. mbuild


m, (foo.m bar.m).  Option
, m, -<arch> (UNIX) <arch>.
, <arch> sol2, hpux glnx86
; @<response_file> (Windows) <response_file>
foo.exe . mbuild response_file
-c , . ,
C .
m foo.m bar.m C  -D<name> C/C ++.
libfoo.dll . : #define<name>
-D<name>#<value> C/C ++.
mcc -W lib:libfoo -T link:lib foo.m bar.m
#define <name> <value>
: -D<name>=<value> (UNIX) C.
libfoo.c C ,  #define <name> <value>
. C -f <<optionsfile>>
. mbuild
m (foo.m bar.m), ; -g (debuggable).
libfoo.h . , mbuild
, libfoo; DEBUGFLAGS
libfoo_mcc_component_data.c C, , DEBUGFLAGS .
mbuild
MCR, .
, -h[elp] . mbuild
MCR; -I<pathname> <pathname>
libfoo.exports , mbuild #include
-inline (mx*)
;
-l<name> (UNIX) lib<name>
libfoo.ctf CTF.  -L<directory> (UNIX) <directory> ,
m, (foo.m bar.m).
, m, -lang <language> . <language>
,  c cpp. , mbuild
(C C++) .
;

libfoo.dll . -n (no exe). ,
mbuild,

6.2.3. mbuild -O
 , .
, ,
.
)g, )O
: -outdir <dirname> , ,
mbuild [option1 ... optionN] sourcefile1 [... sourcefileN] <dirname>.
[objectfile1 ... objectfileN] [libraryfile1 ... libraryfileN] )output )output
[exportfile1 ... exportfileN] -output ,
,  <resultname> <resultname>.
: .c, .cpp, .idl, .rc. .
mbuild
. mbuild ,  )regsvr (Windows) regsvr32
, . . 6.2.1
mbuild. , .
UNIX, Windows. , COM
384 6. MATLAB 4 6.3. mcc 385

6.2.1. mbuild () m, 


Option C C++ m.
-setup
6.3.1. mcc
mbuild
<UserProfile>\Application Data\MathWorks\MATLAB\R14 mcc MATLAB,
(Windows) $HOME/.matlab/R14 (UNIX). DOS (UNIX). 
, ( ) mcc. . 6.3.1
-U<name> C mcc MATLAB, .
<name>. ( )D)
-v .
6.3.1. mcc
,
. /
, , a filename filename
. CTF
B MATLAB Builder for
<name>=<value> (UNIX) <name> . Excel Excel
<value> , B filename )B filename
, , CFLAGS ='opt1 opt2'.
[:arg[,arg]] mcc
, <def>,
filename mcc.
, .
,
, $,
MathWorks,
, CFLAGS = '$CFLAGS opt2'
<name>#<value> <name> . <def> bundles.
, :
, , CFLAGS ='opt1 opt2'. , -B csharedlib:foo
<def>, , C
. -B cpplib:foo
, $, , C++
CFLAGS = '$CFLAGS opt2' C C :
-T codegen
1. (-f, -g, -v) d directory
f filename mbuild )setup
mcc mbuild. , filename,
mbuild
6.3. mcc g

mcc, G .
MATLAB. .
mcc, ,  I directory MATLAB
, ,  m)
C/C ++ . MATLAB,
mcc MATLAB DOS/
UNIX
MATLAB, , , DOS UNIX.
l :
mcc C C++  -W lib -T link:lib
.  m :
. C -W main -T link:exe
mcc: M string mbuild
mcc [-options] mfile1 [mfile2 ... mfileN] [C/C++file1 ... C/C++fileN]
386 6. MATLAB 4 6.3. mcc 387

6.3.1. mcc () b Visual Basic (.bas) 


/ Microsoft Excel COM.
N
MATLAB Builder for Excel.
, B . mcc
. :
o outputfile /) -B filename[:<a1>,<a2>,...,<an>]
filename

mcc / . 
P directory directory )N
-B.
, .
R option option = c C. ,
MCR -nojvm C, mbuild, .
-nojit -T codegen, mcc.
T target target = codegen d .
compile:bin
-d directory
link:bin
where bin =exe .
lib f .
V . .

-f filename
w option option = list
level filename mbuild. 
level:string ANSI 
level =disable MATLAB. mbuild -setup.
enable g .
error .
W type type = main
G . -G,
lib:<string>
none .
com:compname,clname, I .
version -I . :
Y licensefile licensefile -I <directory1> -I <directory2>

, m

z path )
directory1, directory2. ,
MATLAB.
? l .
. m
mcc C, 
mcc . , .
a CTF. m .
-a filename
, -W lib -T link:lib
CTF, -a. m . 
MATLAB, . . :
mbuild, . -W main -T link:exe
388 6. MATLAB 4 6.3. mcc 389

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

6.3.3. . %#external MATLAB,


(mlxF) , .
, , , ,
, MATLAB, ,  m .
, , 
.  , fcn_external.h, fcn
: m, %#external.
; extern, 
MCR. . 
, .
-W <type> C C++ fcn_external.h 
. .
Main. -W main ,  %#function. feval.
. POSIX main :
POSIX . %#function <function_name-list>
m MATLAB. . MATLAB,
2. POSIX Portable Operating System Interface for computer environ feval, eval, 
ments, ( IEEE, . MATLAB,
UNIX).
C. -l, -W lib:libname,  , . 
C.  
m. m, .
C m.  %#function 
,  , ,
C. %#external, . :
C++. -W cpplib:libname  %#function myfunctionwritteninc
C++. , myfunctionwritteninc m, 
m .  , feval. ,
m. .
COM. COM  m,
COM m MATLAB. , %#external,
COM: function y = myfunctionwritteninc( a, b, c );
-W com:<component_name>[,<class_name>[,<major>.<minor>]] %#external
-W excel:<component_name>[,<class_name>[,<major>.<minor>]]
, (a, b, c)
(y). 
6.3.4. m.
m : %#external %#function , 
feval.
C/C++  %#function 
feval.
%#external. C/C ++ 6.3.5. ,
. MATLAB MATLAB:
. m m (). .
%#external m , m . 
396 6. MATLAB 4 6.4. 397

, 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

mlfMrank(1, &R, N); CTF. 


,
/* . */
mlfPrintmatrix(R);  MATLAB
.
/* */ ,
mxDestroyArray(N);
mxDestroyArray(R);
/ . ,
CTF
libPkgTerminate(); /* M- */ .
mclTerminateApplication(); 
}
depfun MATLAB.
mrankp.c mlfMrank (
m mrank.m) , list = depfun('fun');
mlfMrank. MCR libPkg: [list, builtins, classes] = depfun('fun');
mclInitializeApplication(NULL,0); list ( ),
libPkgInitialize();
fun.m (builtins 
, mlfMrank,  , classes ).
libPkg.h: .
void mlfMrank(int nargout, mxArray** r, mxArray* n); :
, mlfMrank  addpath rmpath MATLAB;
. -I <directory> mcc;
mxArray ( ).  -N -p mcc (
mxArray * C mx. ,  ).
11 mxArray *, N,  MATLAB, 
, mrankp mxCreateScalarDouble. addpath rmpath, MATLAB 
N = mxCreateScalarDouble(n); , addpath(list{:}).
mrankp mlfMrank, N :
. MATLAB;
mlfMrank(1,&R,N); MATLAB, ,
mlfMrank MATLAB savepath.
mxArray *, R. R NULL.  ,
, mxArray,  MATLAB.
NULL. R -I, , 
mlfPrintmatrix. m Printmatrix.m.  . , 
, mrankp , MATLAB.
m libPkg MCR. ,
2. <matlabroot>\extern\examples\compiler\ . ,
multarg.m, printmatrix.m multargp.c  MATLAB . -N. -N
,  mcc , 
. ( ):
<matlabroot>/toolbox/matlab
<matlabroot>/toolbox/local
6.4.3. <matlabroot>/toolbox/compiler
. ,
MATLAB . -N
402 6. MATLAB 4 6.4. 403

,  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

3. mclInitializeApplication mlfAddmatrix(1, &out, in1, in2);


/* */
MCR MATLAB .
printf("The value of added matrix is:\n");
, display(out);
MATLAB .  mxDestroyArray(out); out=0;
MCR (MCR instances);
mlfMultiplymatrix(1, &out, in1, in2);
4. <libname>Initialize() printf("The value of the multiplied matrix is:\n");
, MATLAB, display(out);
. mxDestroyArray(out); out=0;
CTF,
mlfEigmatrix(1, &out, in1);
MCR , printf("The Eigen value of the first matrix is:\n");
. true display(out);
false . mxDestroyArray(out); out=0;
5. /* */
( ). C MX API,  libmatrixTerminate();
.
6. <libname>Terminate() ,  /* */
mxDestroyArray(in1); in1=0;
.  mxDestroyArray(in2); in2 = 0;
, MCR. mclTerminateApplication(); /* MCR */
7. mclTerminateApplication, 
, MATLAB. return 1;
}
,
MCR. 3. mclInitializeApplication 
8. , . ., . . 
MathWorks.
matrixdriver.c:
matrixdriver.c 
mbuild, C/C ++:
#include <stdio.h>
mbuild matrixdriver.c libmatrix.lib (Windows)
/* MCR */
#include "mclmcr.h" , , 
#include "libmatrix.h"
int main(){
. , libmatrix.lib.
matrixdriver.exe.
mxArray *in1, *in2; /* */ mlf, m,
mxArray *out = NULL; /* */ . mlf
double data[] = {1,2,3,4,5,6,7,8,9}; :
M
/* mclInitializeApplication */ void mlf<function-name>(<list_of_input_variables>);
if( !mclInitializeApplication(NULL,0) )
{ 
fprintf(stderr, "Could not initialize the application.\n"); void mlf<function-name>(int number_of_return_values,
exit(1); <list_of_pointer_to_return_variables>,
} <list_of_input_variables>);
/* */
in1 = mxCreateDoubleMatrix(3,3,mxREAL); 
in2 = mxCreateDoubleMatrix(3,3,mxREAL); , . , , 
memcpy(mxGetPr(in1), data, 9*sizeof(double));
memcpy(mxGetPr(in2), data, 9*sizeof(double));
, addmatrix
/* */ void mlfAddmatrix(int nlhs,mxArray **a,mxArray *a1,mxArray *a2);
408 6. MATLAB 4 6.5. 409

. . 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

C, , // Call the library function


addmatrix(1, out, in1, in2);
cpplib. ( ):
mcc -W cpplib:libmatrix -T link:lib addmatrix.m multiplymatrix.m // Display the return value of the library function
eigmatrix.m -v std::cout << "The value of added matrix is:" << std::endl;
-W cpplib:<libname> MATLAB std::cout << out << std::endl;
(function wrapper) multiplymatrix(1, out, in1, in2);
<libname>. -T link:lib std::cout << "The value of the multiplied matrix is:"
. , << std::endl;
std::cout << out << std::endl;
libmatrix.dll.
. C++  eigmatrix(1, out, in1);
matrixdriver, matrixdriver.cpp. std::cout << "The eigenvalues of the first matrix are:"
/ *============================================================== << std::endl;
* std::cout << out << std::endl;
* MATRIXDRIVER.CPP }
* Sample driver code that calls a C++ shared library created using catch (const mwException& e)
* the MATLAB Compiler. Refer to the MATLAB Compiler documentation {
* for more information on this std::cerr << e.what() << std::endl;
return -1;
*
}
* This is the wrapper CPP code to call a shared library created
catch (...)
* using the MATLAB Compiler.
{
*
std::cerr << "Unexpected error thrown" << std::endl;
* Copyright 1984-2004 The MathWorks, Inc.
return -1;
*
}
*============================================================*/
// Call the application and library termination routine
// Include the library specific header file as generated by the
libmatrixTerminate();
// MATLAB Compiler
mclTerminateApplication();
#include "libmatrix.h"
return 0;
int main(){
}
// Call application and library initialization. Perform this matrixdriver.cpp C++.
// initialization before calling any API functions or
mbuild:
// Compiler-generated libraries.
if (!mclInitializeApplication(NULL,0) || mbuild matrixdriver.cpp libmatrix.lib (Windows)
!libmatrixInitialize()) C++
{
std::cerr << "could not initialize the library properly"
,
<< std::endl; . :
return -1; mwArray ,
} mxArray, C ;
try C++ .
{ trycatch.
// Create input data C++
double data[] = {1,2,3,4,5,6,7,8,9};
mwArray in1(3, 3, mxDOUBLE_CLASS, mxREAL); m. mlx, 
mwArray in2(3, 3, mxDOUBLE_CLASS, mxREAL); C . 
in1.SetData(data, 9); C++. C++ :
in2.SetData(data, 9);
 ;
// Create output array
mwArray out; void <function-name>(<list_of_input_variables>);
412 6. MATLAB 4 6.5. 413

 . , .
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

Borland C++Builder 6.0


++. Borland C++Builder 6.0 
MATLAB ++. :
1. mk_borland54_libs.bat, 
<matlab>\extern\lib\win32.
7. , MATLAB 
MATLAB .
Borland ++ Builder DOS <matlab>\extern\lib\win32. 
++ MATLAB , .
2. Project Options.
Windows Directories/Conditionals.
Borland ++ Builder 6 Include :
++ MATLAB. C:\MATLAB6p5\extern\include;
C:\MATLAB6p5\extern\include\cpp;
Borland C++ Builder
Library lib
<matlab>\extern\examples\cppmath\borland\readme 
C:\MATLAB6p5\extern\lib\win32;
,  C:\MATLAB6p5\extern\lib\win32\borland\bc54
Borland C++Builder 3.0, Borland C 5.3
3. lib
Borland C++Builder 4.0, Borland C 5.4,
Borland. Project
C/++. 
Add to Project _libmat.lib, _libmatlb.lib, _libmmfile.lib,
ex1.cpp ( /
_libmx.lib libmatpb54.lib c:\MATLAB6p5\extern\lib\win32\,
) <matlab>\extern\
, lib c:\MATLAB6p5\
examples\cppmath. Borland C++Builder 4.0 
extern\lib\win32\borland\bc54.
:
4. Borland C++ Builder 6 
1. mk_borland54_libs.bat,  . <matlab>\extern\include\cpp 
<matlab>\extern\lib\win32. MATLAB Borland
, MATLAB  C++ Builder .
MATLAB . . , 
DOS <matlab>\extern\lib\win32.  ,
(*.lib) def,  ,
. , Borland C++Builder , , .
4.0 lib def. , . 
2. Borland C++Builder 4.0 borland54.bpr , , Podkur.exe 
<matlab>\extern\examples\cppmath\borland. . , mltif.h 
3. Project Options. pascal ( 11668) pascal_.
Directories/Conditionals. 5. 
Include MATLAB ++.
C:\MATLAB6p5\extern\include\
Library
C:\MATLAB6p5\extern\lib\win32\
7.1. ,
C:\MATLAB6p5\extern\lib\win32\borland\bc54\. (Project_71),
MATLAB ASCII,
Borland C++Builder,  ++ MATLAB 
C/++, Borland C 5.4. ASCII.
416 7. 7.1. , 417

 #include "matlab.hpp" // Math Library ++


(), . #include "matrix.h"
#include "Unit_71.h"
. . //
, #pragma package(smart_init)
. #pragma resource "*.dfm"
. TForm1 *Form1;
( )  // -
.  __fastcall TForm1::TForm1(TComponent* Owner)
. : TForm(Owner)
{
++ MATLAB: }
fopen ;
fscanf ;
fclose ;
fprintf ;
extractScalar mwArray ;
size ;
mclGetInf , ;
ctranspose ;
detrend ( );
horzcat ;
vertcat .
. 7.1.1. Form1 Project_71
, , Unit_71.cpp.
. . ,
. ,  . .
, , : realdata, double,
NCh0 = 0 , mwArray; Edit3 Edit4.
NLen0 = 0 , mwArray;
NCh , mwArray;
mwArray NCh0 = 0; //
iNCh , int; mwArray NLen0 = 0; //
NLen , mwArray;
iNLen , int; mwArray NCh; //
Sig , mwArray; int iNCh; //
SigDt , mwArray; mwArray NLen; //
MaxY, MinY , mwArray; int iNLen; //
DOut , mwArray.
mwArray Sig; //
Unit_71.cpp .  mwArray DOut; //
Form1. mwArray Y;
.  mwArray SigDt; //
matlab.hpp matrix.h C/++ mwArray MaxY;
mwArray MinY;
MATLAB. double *realdata = new double [2*8]; // ++ mwArray
// Unit_71.cpp

#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); //

DOut=vertcat(MaxY, MinY); // 2--8


mwArray TOut = ctranspose(DOut); //
// mwArray ++ . 7.1.2. Project_71
TOut.ExtractData(realdata); // mwArray
// realdata
}
} 7.2. mwArray
void __fastcall TForm1::Edit5Change(TObject *Sender) Borland C++ Builder,
{
int k = StrToInt(Edit5->Text);

Edit3->Text = FloatToStr(realdata[k-1]); // max ASCII,
Edit4->Text = FloatToStr(realdata[k+7]); // main . ,
422 7. 7.2. mwArray 423

mwArray , mwArray SigTrDt = detrend(SigTr,"constant");


DynamicArray. MaxY = max(SigTrDt); // max
MinY = min(SigTrDt); // min
, , SigDt = ctranspose(SigTrDt);
( , ) . 
, , 
, , Unit_72.cpp. 
, ,
(Project_72) Glava_7\Project_72\ 
. Unit_72.cpp, :
. Test_Sig.txt, Test_ if ((iNLen - PaintBox1->Width)<0)
// , , ,
SigD.txt Test_SigD2.txt Glava_7\Project_72\ //
. // .
Form1 . ,  ScrollBar1->Max = 0;
: Panel2,  else
// ,
, // ,
ScrollBar1 PaintBox1. // . ,
//
// , .
ScrollBar1->Max = iNLen - PaintBox1->Width;

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

Tmp = SigDt(NCh, NN+1);


int y = floor(WinH*(mMaxY-Tmp.ExtractScalar(1))/(mMaxY-mMinY))+
WinH*(NCh-1);
PaintBox1->Canvas->MoveTo(0,y);

//
// .
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 idwtA(mwArray cA, mwArray LoR, mwArray NS) 


{
.  
mwArray Len_cA = length(cA); //
mwArray Len2cA = Len_cA*2; // 2* , , 
mwArray c2A = zeros(1,Len2cA); . . . 7.3.3 7.3.4.
Unit1.cpp.
c2A(colon(2,2,Len2cA)) = cA;
Project_72,
mwArray idwtSA,idwtSNA; . .
idwtSA = conv(LoR,c2A); Unit1.cpp .
1. . Sig,
mwArray Len_idwtSA = length(idwtSA);
mwArray Res = ceil((Len_idwtSA - NS)/2);
NCh0, NLen0. ,
idwtSNA=idwtSA(colon(Res,1,Res+NS-1)); . . 
FragSig FragLen. 
return idwtSNA; Project_72.
}
3. . Spfft
Y = fft(X)
, N . Spfft:

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

5 ,  Suppw (Suppw = LF 1);


. , iSuppw .
, .  
, . , Edit8 Edit9.
fscanf . , :
(, db2.txt  // -
): void __fastcall TForm1::N6Click(TObject *Sender)
Wfilters 5LF ; {
if(OpenDialog1->Execute())
LoD , 1 Wfilters; {
HiD , 2; mwArray WLen = mclGetInf(); //
LoR (), 3; mwArray u;
HiR , 4; mwArray mod("rt");
mwArray fil(OpenDialog1->FileName.c_str());
Frw , 5 ; u = fopen(fil, mod);
LF ; Wfilters = fscanf(u, "%g ", horzcat(5, WLen));
iLF ; fclose(u);

LoD = Wfilters (1, colon());


HiD = Wfilters (2, colon());
LoR = Wfilters (3, colon());
HiR = Wfilters (4, colon());
Frw = Wfilters(5,1);
double fFrw = Frw.ExtractScalar(1);
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); //
}
}

//
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);

LoD = Wfilters (1, colon());


HiD = Wfilters (2, colon());
LoR = Wfilters (3, colon());
HiR = Wfilters (4, colon());

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

for(int p=1; p < 3; p++) // p 4. .


{ 72.
mwArray coefAj = dwt(LoD, TwCoef.cell(j- 1,K)(p,colon()));
int q = 2*p-1; , 
TwCoef.cell(j,K)(q,colon())= coefAj; PaintBox4.
int q2 = 2*p; Unit1.cpp 
mwArray coefDj =dwt(HiD, TwCoef.cell(j-1,K)(p,colon()));
TwCoef.cell(j,K)(q2,colon())= coefDj; Glava_7\Project_73\.
LenCoef(j+1) = length(coefDj); // -
} // p void __fastcall TForm1::ScrollBar2Change(TObject *Sender)
} // j {
PaintBox4->Refresh();
// - }
// , // -
//
void __fastcall TForm1::PaintBox4Paint(TObject *Sender)
// j=2 {
if (ready2) {
mwArray R21A=idwtA(TwCoef.cell(2,K)(1,colon()), LoR,LenCoef(2)); TRect R1, R2; //
TwComp.cell(2,K)(1,colon()) = idwtA(R21A,LoR,LenCoef(1)); //
SpecComp.cell(2,K)(1,colon())= Spfft(TwComp.cell(2,K)(1,colon())); R1.Left = 2;
R1.Top = 2;
mwArray R22D=idwtD(TwCoef.cell(2,K)(2,colon()), HiR,LenCoef(2)); R1.Right = PaintBox4->Width-2;
TwComp.cell(2,K)(2,colon()) = idwtA(R22D,LoR,LenCoef(1)); R1.Bottom = (PaintBox4->Height-23)/2;
SpecComp.cell(2,K)(2,colon())= Spfft(TwComp.cell(2,K)(2,colon()));
//
mwArray R23A=idwtA(TwCoef.cell(2,K)(3,colon()), LoR,LenCoef(2)); R2.Left = 2;
TwComp.cell(2,K)(3,colon()) = idwtD(R23A,HiR,LenCoef(1)); R2.Top = R1.Bottom;
SpecComp.cell(2,K)(3,colon())= Spfft(TwComp.cell(2,K)(3,colon())); R2.Right = PaintBox4->Width-2;
R2.Bottom = PaintBox4->Height-23;
mwArray R24D=idwtD(TwCoef.cell(2,K)(4,colon()), HiR,LenCoef(2));
TwComp.cell(2,K)(4,colon()) = idwtD(R22D,HiR,LenCoef(1)); //
SpecComp.cell(2,K)(4,colon())= Spfft(TwComp.cell(2,K)(4,colon())); PaintBox4->Canvas->MoveTo(R1.Left,R1.Top);
PaintBox4->Canvas->LineTo(R2.Left,R2.Bottom);
// j=3
//
mwArray R31A=idwtA(TwCoef.cell(3,K)(1,colon()), LoR,LenCoef(3)); PaintBox4->Canvas->MoveTo(R1.Left,R1.Bottom);
mwArray R31AA=idwtA(R31A,LoR,LenCoef(2)); PaintBox4->Canvas->LineTo(R1.Right,R1.Bottom);
TwComp.cell(3,K)(1,colon()) = idwtA(R31AA,LoR,LenCoef(1));
SpecComp.cell(3,K)(1,colon())= Spfft(TwComp.cell(3,K)(1,colon())); //
PaintBox4->Canvas->MoveTo(R2.Left,R2.Bottom);
mwArray R32D=idwtD(TwCoef.cell(3,K)(2,colon()), HiR,LenCoef(3)); PaintBox4->Canvas->LineTo(R2.Right,R2.Bottom);
mwArray R32DA=idwtA(R32D,LoR,LenCoef(2));
TwComp.cell(3,K)(2,colon()) = idwtA(R32DA,LoR,LenCoef(1)); //
SpecComp.cell(3,K)(2,colon())= Spfft(TwComp.cell(3,K)(2,colon())); PaintBox4->Canvas->TextOut(R2.Left, R2.Bottom+2,
IntToStr(ScrollBar2->Position));
mwArray R33A=idwtA(TwCoef.cell(3,K)(3,colon()), LoR,LenCoef(3)); PaintBox4->Canvas->TextOut(R2.Right-PaintBox4->Canvas
mwArray R33AD=idwtD(R32D,HiR,LenCoef(2)); ->TextWidth(IntToStr(ScrollBar2->Position+KMax)),
TwComp.cell(3,K)(3,colon()) = idwtA(R33AD,LoR,LenCoef(1)); R2.Bottom+2, IntToStr(ScrollBar2->Position+KMax));
SpecComp.cell(3,K)(3,colon())= Spfft(TwComp.cell(3,K)(3,colon()));
//
mwArray R34D=idwtD(TwCoef.cell(3,K)(4,colon()), HiR,LenCoef(3)); // SelCh MaxY MinY -
mwArray R34DD=idwtD(R34D,HiR,LenCoef(2)); mwArray Tmp = FragSig(SelCh,colon());
TwComp.cell(3,K)(4,colon()) = idwtA(R34DD,LoR,LenCoef(1)); mwArray TmpTr = ctranspose(Tmp);
SpecComp.cell(3,K)(4,colon())= Spfft(TwComp.cell(3,K)(4,colon()));
mwArray MaxY = max(TmpTr); // max-
} // K double mMaxY = MaxY.ExtractScalar(1);
}
} mwArray MinY = min(TmpTr); // min-
436 7.
double mMinY = MinY.ExtractScalar(1);
//
int x = R1.Left;
int y = R1.Top + floor((R1.Bottom-R1.Top)*(mMaxY
Tmp.ExtractScalar(1+ScrollBar2->Position))/(mMaxY-mMinY));
PaintBox4->Canvas->MoveTo(x, y);

// 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

ferror / ; or_func OR (|);


frewind ; xor_func OR.
fseek ;
ftell . intersect ;
/ ismember , ;
fgetl , ; setdiff ;
fgets , ; setxor OR;
fprintf ; union_func ;
fscanf . unique .

fread ; colon (:);
fwrite . ctranspose (');
end ;
sprintf ; horzcat ;
sscanf . transpose (.');
vertcat .

1.2.2. find ;
finite ;
kron () ; ischar ;
minus (); isempty , ;
mldivide (\); isfinite , ;
mpower ; isieee IEEE ;
mrdivide (/); isequal , 
mtimes (*); ;
plus (+); isinf ;
power ; isletter ;
rdivide (./); islogical ;
times ; isnan ;
unaryminus . isreal () ;
isspace ;
eq (==); isstr ;
ge (>=); isstudent MATLAB;
gt (>); isunix UNIX;
le (<=); isvms VMS DEC;
lt (<); logical ;
neq (~=). tobool
.
all , ;
and_func AND (&); bitand_func AND;
any ,  ; bitcmp (Complement bits);
not_func NOT (~); bitget (Get bit);
442 1. C++ .1.2. 443

bitmax (Maximum diag ;


floatingpoint integer); fliplr / ;
bitor_func OR; flipud /;
bitset (Set bit); ipermute ;
bitshift (Bitwise shift); permute ;
bitxor XOR. repmat ;
MATLAB reshape ;
feval () ; rot90 90;
lasterr ; shiftdim ;
mfilename m; tril ;
nargchk ; triu .
error ;
warning . compan ,
;
1.2.3. hadamard ;
hankel ;
hilb ;
invhilb ;
eye ; magic ;
linspace [a, b], pascal, pascal_func ;
; rosser , 
logspace [a, b],  ;
; toeplitz ;
meshgrid X Y  vander ;
; wilkinson ,
ones ; .
rand ;
randn ; 1.2.4.
zeros .
. .
cos, cosh, cot, coth, csc, csch, sec, sech, sin, sinh, tan, tanh, acos, acosh, acot, acoth,
disp ; acsc, acsch, asec, asech, asin, asinh, atan, atanh, atan2 (
isempty , ; (pi,pi)).
isequal ,
; exp ;
islogical ; log ;
isnumeric ; log10 10;
length ; log2 2;
logical ; nextpow2 2;
ndims ; pow2 2^x;
size . reallog log ();
reallog10 log10 ();
cat ; realpow ();
444 1. C++ .1.2. 445

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

. MATLAB (:), . end


, MATLAB A(3,6:end). x , 
. C++, , 1 , 2 
MATLAB C++ , ramp() colon(), . y .
. ramp()
, colon()
. .
.1.4.

mwArray ramp(mwArray start, mwArray end);
mxArray. 
mx.
(endstart)+1 . : start,
, mxArray *
start+1, start+2, ... , start+n, end. ,
mwArray. , mxCreateDoubleMatrix()
, (.
mxArray; mxDestroyArray() .
).
MATLAB Application Program

Interface Reference MATLAB Application Program Interface Guide.
mwArray ramp(mwArray start, mwArray step, mwArray end);
((endstart)/step)+1 . start, .1.5.
start+step, start+(2*step), start+(3*step), ...,start+(n*step), end.

, ,
mxCalloc, mxFree ,
. , start+(n*step)
MATLAB
, ; mxClearLogical
mxCreateCellArray N)
.  mxArray
. , ,  mxCreateCellMatrix 2)
. mxArray
. mxCreateCharArray N)
mxArray
mwIndex
colon(); mxCreateCharMatrix 2)
FromStrings mxArray
. colon() . mxCreateDoubleMatrix
, A(colon()) . A(1, colon()) mxArray
. mxCreateNumericArray mxArray
mxCreateSparse mxArray
mwIndex mxCreateString 1))n mxArray
colon(mwArray start, mwArray end);
ramp(), , ,  mxCreateStructArray N)
mxArray
.
mxCreateStructMatrix mxArray
mxDestroyArray ,
mwIndex mxCreate
colon(mwArray start, mwArray step, mwArray stop); mxDuplicateArray
ramp(), , ,  mxGetCell
. mxGetClassID ( ) mxArray
mxGetClassName ( ) mxArray
mwArray mxGetData
end(mwArray &mat, mwArray &x, mwArray &y); mxGetDimensions
456 1. C++ .1.4. 457

.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

mwString(const char* str);


mwString(const mwString& str);

int Length() const.

2. C++ operator const char* () const;
4 MATLAB mwString& operator=(const mwString& str);
mwString& operator=(const char* str);
C++  bool operator==(const mwString& str) const;
4 MATLAB R 14. ,  bool operator!=(const mwString& str) const;
MATLAB, : bool operator<(const mwString& str) const;
mwString. , mwArray API (MATLAB bool operator<=(const mwString& str) const;
Application Program Interface) ; bool operator>(const mwString& str) const;
mwException. , API C++ bool operator>=(const mwString& str) const;
; friend std::ostream& operator<<(std::ostream& os, const mwString& str).
mwArray. /
C++ , MATLAB.
2.2.1.
mwString(). .
.2.1. C++ :
mwArray API ,  #include "mclcppclass.h"
MATLAB. . mwString str;
. .
.2.1. . .
Type . mxClassID mwString(const char* str).
mxChar mxCHAR_CLASS .
mxLogical mxLOGICAL_CLASS C++ :
mxDouble double mxDOUBLE_CLASS #include "mclcppclass.h"
mxSingle mxSINGLE_CLASS mwString str("This is a string");
mxInt8 , 1)byte mxINT8_CLASS . str. ( NULL ) .
mxUint8 , 1)byte mxUINT8_CLASS
. .
mxInt16 , 2)byte mxUINT16_CLASS
mxUint16 , 2)byte mxUINT16_CLASS
.
mxInt32 , 4)byte mxINT32_CLASS ( NULL ) .
mxUint32 , 4)byte mxUINT32_CLASS mwString(const mwString& str). mwString.
mxInt64 , 8)byte mxINT64_CLASS mwString.
mxUint64 , 8)byte mxUINT64_CLASS C++ :
#include "mclcppclass.h"
mwString str("This is a string");
.2.2. mwString mwString new_str(str); // new_str contains a copy of the
// characters in str.
, mwArray API, . str. mwString .
. . .
. 
mwString(); mwString.
460 2. C++ .2.2. mwString 461

mwString str2("This is another string");


2.2.2. bool ret = (str == str2); // ret should have a value of false.
int Length() const. . . str. .
C++ : . .
#include "mclcppclass.h" . .
mwString str("This is a string"); bool operator!=(const mwString& str) const. mwStrings
int len = str.Length(); // len should be 16.
.
. . C++ :
. . #include "mclcppclass.h"
. mwString.  mwString str("This is a string");
NULL. mwString str2("This is another string");
bool ret = (str != str2); // ret should have a value of true.

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

friend std::ostream& operator<<(std::ostream& os, const mwString& str). C++ :


ostream. #include "mclcppclass.h"
C++ : try
{
#include "mclcppclass.h"
throw mwException("This is an error");
#include <ostream>
}
mwString str("This is a string");
catch (const mwException& e)
std::cout << str << std::endl; // should print "This is a
{
// string" to standard out.
std::cout << e.what() << std::endl;// Displays "This is an error" to
. // standard out.
os. ostream ; }
str. . . msg. .
. ostream. . .
. mwString ostream. . an mwException 
.
mwException(const mwException& e). mwException
.2.3. mwException .
, mwArray API C++ C++ :
. , mwArray API #include "mclcppclass.h"
C++, MATLAB, try
mwExceptions. {
throw mwException("This is an error");
}
mwException() ; catch (const mwException& e)
mwException(const char* msg); {
mwException(const mwException& e); throw mwException(e); // Rethrows same error.
}
mwException(const std::exception& e).
. e. mwException .

. .
const char *what() const throw().
. mwException.
, .
mwException& operator=(const mwException& e); mwException(const std::exception& e). mwException 
mwException& operator=(const std::exception& e). std::exception.
C++ :
2.3.1. #include "mclcppclass.h"
try
mwException(). mwException  {
. ....
}
C++ :
catch (const std::exception& e)
#include "mclcppclass.h" {
throw mwException(); throw mwException(e); // Rethrows same error.
. . }
. . . e. std::exception .
. an mwException . .
. . mwException
mwException(const char* msg). mwException
. std::exception.
464 2. C++ .2.4. mwArray 465

catch (const std::exception& e)


2.3.2. {
mwException e2 = e;
const char *what() const throw(). ,  throw e2;
. }
C++ : . e. std::exception .
#include "mclcppclass.h" . mwException.
try
{ . std::exception.
.... , .
}
catch (const std::exception& e)
{ .2.4. mwArray
std::cout << e.what() << std::endl; // Displays the error
// message to
,  C++
// standard out. , MATLAB.
} MATLAB. mwArray
. . , ,
. NULL .
.
. (retrieve) mwArray();
mwException. mwArray(mxClassID mxID);
mwArray(int num_rows, int num_cols, mxClassID mxID, mxComplexity
2.3.3. cmplx = mxREAL);
mwArray(int num_dims, const int* dims, mxClassID mxID, mxComplexity
mwException& operator=(const mwException& e). cmplx = mxREAL);
mwException.. mwArray(const char* str);
C++ : mwArray(int num_strings, const char** str);
#include "mclcppclass.h" mwArray(int num_rows, int num_cols, int num_fields, const char**
try
{
fieldnames);
... mwArray(int num_dims, const int* dims, int num_fields, const char**
} fieldnames);
catch (const mwException& e) mwArray(const mwArray& arr);
{
mwException e2 = e; mwArray(<type> re);
throw e2; mwArray(<type> re, <type> im).
}

. e. mwException . mwArray Clone() const;
. mwException. mwArray SharedCopy() const;
. mwException. mwArray Serialize() const;
, . mxClassID ClassID() const;
mwException& operator=(const std::exception& e). int ElementSize() const;
mwException. int NumberOfElements() const;
C++ : int NumberOfNonZeros() const;
#include "mclcppclass.h" int MaximumNonZeros() const;
try
int NumberOfDimensions() const;
{
... int NumberOfFields() const;
} mwString GetFieldName(int index);
466 2. C++ .2.4. mwArray 467

mwArray GetDimensions() const; . .


bool IsEmpty() const; . 
bool IsSparse() const; .
bool IsNumeric() const; mwArray(mxClassID mxID). .
bool IsComplex() const; C++ :
bool Equals(const mwArray& arr) const; #include "mclcppclass.h"
int CompareTo(const mwArray& arr) const; mwArray a(mxDOUBLE_CLASS);
int HashCode() const; . .
mwString ToString() const; . 
mwArray RowIndex() const;
. mxClassID.
mwArray ColumnIndex() const;
mwArray(int num_rows, int num_cols, mxClassID mxID, mxComplexity
void MakeComplex();
cmplx = mxREAL). . 
mwArray Get(int num_indices, ...);
.
mwArray Get(const char* name, int num_indices, ...);
mwArray GetA(int num_indices, const int* index); C++ :
mwArray GetA(const char* name, int num_indices, const int* index); #include "mclcppclass.h"
mwArray a(2, 2, mxDOUBLE_CLASS);
mwArray Real(); mwArray b(3, 3, mxSINGLE_CLASS, mxCOMPLEX);
mwArray Imag(); mwArray c(2, 3, mxCELL_CLASS);
void Set(const mwArray& arr);
.
void GetData(<numerictype>* buffer, int len) const;
num_rows ;
void GetLogicalData(mxLogical* buffer, int len