爱情 (1) 安装 (2) 北斗 (1) 毕业 (1) 变量 (1) 测绘局 (1) 测量 (2) 插件 (1) 查询 (1) 常用 (1) 成果转化 (1) 词汇 (1) 慈善 (1) 答辩 (2) 代码 (2) 电台 (1) 发泄 (1) 感悟 (4) 高程 (1) 搞笑 (5) 共产党 (1) 古诗词 (1) 管理 (1) 函数 (3) 绘图 (1) 加密 (1) 交际 (1) 教程 (4) 教育 (2) 解决 (4) 解密 (1) 精度 (1) 酒桌 (2) 开源 (2) 科技 (1) 科学 (1) 刻录 (1) 老外 (1) 励志 (5) 连续剧 (1) 恋爱 (1) 列表 (1) 领导 (1) 美食 (2) 名人 (3) 命令 (4) 区别 (1) 日记 (2) 软件 (12) 商业 (3) 时政 (1) 视频 (1) 数据 (1) 算法 (1) 投影 (2) 图论 (1) 网络 (1) 网站 (1) 卫星 (3) 未成年 (1) 慰问 (1) 文本 (1) 文件 (2) 下载 (4) 笑话 (2) 学习 (9) 遥感 (1) 疑问 (5) 营销 (1) 娱乐 (3) 源代码 (2) 政策 (1) 指导 (3) 智慧 (5) 主成分分析 (2) 抓图 (1) 专家 (1) 资料 (5) 字符串 (1) 最短路径 (1) 坐标 (1) baidu (3) Bernese (1) blog (2) c# (9) China (3) Dijkstra (1) DNS (1) doris (1) dos (1) excel (1) firefox (3) GAMIT (8) gcc (1) GIS (3) GMT (1) GPS (5) ITRF (1) linux (5) mapx (1) matlab (6) movie (4) music (3) oracle (2) pic (1) PPT (3) PROJ.4 (2) python (2) QQ (2) rinex (1) shell (2) sql (1) teqc (3) tools (1) tps (1) ubuntu (5) USA (1) website (1)
显示标签为“matlab”的博文。显示所有博文
显示标签为“matlab”的博文。显示所有博文

2010年5月15日星期六

M_Map: A mapping package for Matlab

http://www.eos.ubc.ca/~rich/map.html

Instead you have to figure out how to save all your data, and then read it into another program (like, for example GMT ), and then spend all that extra time figuring out why it doesn't give you what you expected it would...or you can invest in Matlab's own mapping toolbox (with a similarly steep learning curve)... or not!

M_Map is a set of mapping tools written for Matlab v5 and later. These include:

  1. Routines to project data in 19 different spherical projections (and determine inverse mappings)
  2. A grid generation routine to make nice axes with limits either in lat/long terms or in planar X/Y terms.
  3. A coastline database (with 1/4 degree resolution)
  4. A global elevation database (1 degree resolution)
  5. Hooks into freely available high-resolution coastline and bathymetry databases

Announcing M_Map v1.4e! (updated Oct/09)


















2010年5月13日星期四

主成分分析(PCA)Matlab源码

主成分分析(PCA)Matlab源码

principal component analysis(PCA)主成分分析,Matlab实例代码
  1. function main()
  2. %*************主成份分析************
  3. %
  4. %see also http://www.matlabsky.com
  5. %
  6. %读入文件数据
  7. X=load('data.txt');
  8. %==========方法1:求标准化后的协差矩阵,再求特征根和特征向量=================
  9. %标准化处理
  10. [p,n]=size(X);
  11. for j=1:n
  12. mju(j)=mean(X(:,j));
  13. sigma(j)=sqrt(cov(X(:,j)));
  14. end
  15. for i=1:p
  16. for j=1:n
  17. Y(i,j)=(X(i,j)-mju(j))/sigma(j);
  18. end
  19. end
  20. sigmaY=cov(Y);
  21. %求X标准化的协差矩阵的特征根和特征向量
  22. [T,lambda]=eig(sigmaY);
  23. disp('特征根(由小到大):');
  24. disp(lambda);
  25. disp('特征向量:');
  26. disp(T);
  27. %方差贡献率;累计方差贡献率
  28. Xsum=sum(sum(lambda,2),1);
  29. for i=1:n
  30. fai(i)=lambda(i,i)/Xsum;
  31. end
  32. for i=1:n
  33. psai(i)= sum(sum(lambda(1:i,1:i),2),1)/Xsum;
  34. end
  35. disp('方差贡献率:');
  36. disp(fai);
  37. disp('累计方差贡献率:');
  38. disp(psai);
  39. %综合评价....略
复 制代码

本帖隐藏的内容需要回复才可以浏览

  1. %
  2. %
  3. %============方法2:求X的相关系数矩阵,再求特征根和特征向量================
  4. %X的标准化的协方差矩阵就是X的相关系数矩阵
  5. R=corrcoef(X);
  6. %求X相关系数矩阵的特征根和特征向量
  7. [TR,lambdaR]=eig(R);
  8. disp('特征根(由小到大):');
  9. disp(lambdaR);
  10. disp('特征向量:');
  11. disp(TR);
复制 代码

matlab 把变量保存到 文件中去

变量 保存的 文本文件中去,
save('文件名','变量名','-ASCII');

但保存的结果是科学计数法的,1.9992e-03
如何在处理为普通的数值呢??

2010年5月12日星期三

matlab 变量名自动增加

采用cell 的方法了。
im=imread('3.png');
s{1} = imcrop(im,[0,0,128,128]);
s{2} = imcrop(im,[0,0,64,64]);
s{3} = imcrop(im,[64,0,64,64]);
s{4} = imcrop(im,[0,64,64,64]);
s{5} = imcrop(im,[64,64,64,64]);

想用for循环显示
for i=1:4
image( s{i} );
end
取第一个cell中的第一列:
contantAll{1,1}(:,1)

matlab-统计概率工具箱详解——主成分析

主 成分析是把多个指标化为少数几个综合指标的一种统计方法。在多变量研究中,往往由于变量个数太多,并且彼此之间存在一定的 相关性,使得观测数据在一定程度上反映的信息有所重叠。利用主成分析则可 以将这一问题化简,即通过降维,找出几个综合因子来代表原来众多 变量,使这些综合因子尽可能反应原来变量的信息量,而其彼此之间互不相关。

1、bartlett维数检验
[ndim,prob,chi]=barttest(x,alpha)
用给定的显著性概率alpha,返回维数、显著性概率和卡方值,用于解释x数据矩阵的非随即变化特征。维数由一系列假设检验确定。假设 ndim=1的检验是检验与每个因子一起的方差是否相等;ndim=2的检验则检验第2个因子至最后一个因子一起的方差是否相等,依此类推。。。


2、使用协方差矩阵进行主成分析
[pc,latent,explained]=pcacov(X)
利用协方差矩阵X,返回主要因子pc、协方差矩阵的特征值latent、观测量中每一个特征向量所解释的总方差百分比explained。
  1. >> clear
  2. >> load hald
  3. >> covx=cov(ingredients)
  4. >> [pc,variances,explained]=pcacov(covx)

  5. pc =

  6. -0.0678 0.6460 -0.5673 0.5062
  7. -0.6785 0.0200 0.5440 0.4933
  8. 0.0290 -0.7553 -0.4036 0.5156
  9. 0.7309 0.1085 0.4684 0.4844


  10. variances =

  11. 517.7969
  12. 67.4964
  13. 12.4054
  14. 0.2372


  15. explained =

  16. 86.5974
  17. 11.2882
  18. 2.0747
  19. 0.0397
复 制代码
3、计算源于主成分析的残差
pcares(X,ndim)
通过保留X的ndim个因子成分来获得残差,注意,ndim为标量并且必须小于X的列数。将数据矩阵、协方差和该函数一起使用。
  1. >> r1=pcares(ingredients,1);
  2. >> r2=pcares(ingredients,2);
  3. >> r3=pcares(ingredients,3);

  4. >> r11=r1(1,:)

  5. r11 =

  6. 2.0350 2.8304 -6.8378 3.0879

  7. >> r21=r2(1,:)

  8. r21 =

  9. -2.4037 2.6930 -1.6482 2.3425

  10. >> r31=r3(1,:)

  11. r31 =

  12. 0.2008 0.1957 0.2045 0.1921
复制代码
4、主成分析
[pc,score,latent,tsquare]=princomp(X)
根据数据矩阵返回因子成分pc、z分数score、特征值latent和Hotelling的T2统计量tsquare。Z分数是 通过将原来数据转换到因子成分空间得到的数据;latent向量的值为score的列数据的方差;Hotelling的T2为来自 数据集合中心的每一个观测量的多变量距离的度量。
  1. %为 ingredients数据计算因子成分,及由每个成分解释的方差
  2. >> [pc,score,latent,tsquare]=princomp(ingredients)

  3. pc =

  4. 0.0678 0.6460 -0.5673 0.5062
  5. 0.6785 0.0200 0.5440 0.4933
  6. -0.0290 -0.7553 -0.4036 0.5156
  7. -0.7309 0.1085 0.4684 0.4844


  8. score =

  9. -36.8218 6.8709 4.5909 0.3967
  10. -29.6073 -4.6109 2.2476 -0.3958
  11. 12.9818 4.2049 -0.9022 -1.1261
  12. -23.7147 6.6341 -1.8547 -0.3786
  13. 0.5532 4.4617 6.0874 0.1424
  14. 10.8125 3.6466 -0.9130 -0.1350
  15. 32.5882 -8.9798 1.6063 0.0818
  16. -22.6064 -10.7259 -3.2365 0.3243
  17. 9.2626 -8.9854 0.0169 -0.5437
  18. 3.2840 14.1573 -7.0465 0.3405
  19. -9.2200 -12.3861 -3.4283 0.4352
  20. 25.5849 2.7817 0.3867 0.4468
  21. 26.9032 2.9310 2.4455 0.4116


  22. latent =

  23. 517.7969
  24. 67.4964
  25. 12.4054
  26. 0.2372


  27. tsquare =

  28. 5.6803
  29. 3.0758
  30. 6.0002
  31. 2.6198
  32. 3.3681
  33. 0.5668
  34. 3.4818
  35. 3.9794
  36. 2.6086
  37. 7.4818
  38. 4.1830
  39. 2.2327
  40. 2.7216
复 制代码



应用Matlab内部数据cites.mat进行分析。该数据是美国329个城市反应生活质量的9项指标 的数据。9项指标依次为:气候、住房、健康、犯罪、交通、教育、艺术、娱乐和经济。

首先载入数据,包含3个变量
  1. >> clear
  2. >> load cities
  3. >> who

  4. Your variables are:

  5. categories names ratings
复制代码
用箱图表达下:
  1. >> boxplot(ratings,0,'+',0)
  2. >> set(gca,'yticklabel',categories)
复制代码

从图可以看出,艺术和住房的变化很大,气候的变化很小。

当原始数据的量级和量纲存在较大差异时,需要先对数据进行标准化,然后进行主成分析。标准化的方法是将原始数据的各列除以各列的标准差:
  1. stdr=std(ratings);
  2. sr=ratings./stdr(ones(329,1),:);
复制代码
现在寻找主要成分:
  1. [pcs,newdata,var,ts]=princomp(sr);
复制代码
(1)第一个输出——主成分pcs
pcs包括9个主成分,下面只是给出前四列
>> p4=pcs(:,1:4)

p4 =

0.2064 0.2178 -0.6900 0.1373
0.3565 0.2506 -0.2082 0.5118
0.4602 -0.2995 -0.0073 0.0147
0.2813 0.3553 0.1851 -0.5391
0.3512 -0.1796 0.1464 -0.3029
0.2753 -0.4834 0.2297 0.3354
0.4631 -0.1948 -0.0265 -0.1011
0.3279 0.3845 -0.0509 -0.1898
0.1354 0.4713 0.6073 0.4218[/code]
可以看出第一个主成分中第7个元素的权重最大。
可以通过查看p3乘以p3T的结果来判断其正交性:
  1. >> p4'*p4

  2. ans =

  3. 1.0000 -0.0000 0.0000 -0.0000
  4. -0.0000 1.0000 0.0000 -0.0000
  5. 0.0000 0.0000 1.0000 -0.0000
  6. -0.0000 -0.0000 -0.0000 1.0000
复制代码
计算结果为单位矩阵,说明主成分之间满足正交。

(2)第2个输出——主成分得分(newdata)
主成分得分是原始数据在主成分所定义的新坐标系中的确定的数据,其大小与输入数据矩阵大小相同。
下面我们看看newdata的前两列数据作为前两个主成分时的结果:
  1. >> x=newdata(:,1);
  2. >> y=newdata(:,2);
  3. >> plot(x,y,'+')
  4. >> xlabel('第一主成分')
  5. >> ylabel('第二主成分')
复制代码

从图像可以看出,在右侧有一些异常点。可以使用gnames()函数标注图中的点,下面使用字符串矩阵names调用gnames:
  1. >> gname(names)
复制代码
此时将在图像中生成一个十字交叉线,交点跟随鼠标移 动。在散点附近单击,将标注该点的字符串。标注结束后,敲回车。结果显示如下:


对于这些异常值我们可以直接删除,也即是将那几行的元素直接置空,比如New York对应第213行:
  1. rsubset=ratings;
  2. rsubset(213,:)=[];
复制代码
(3)第3个输出——主成分方差(var)
主成分方差var是有newdata的对应列所解释的包含方程的向量:
  1. >> var

  2. var =

  3. 3.4083
  4. 1.2140
  5. 1.1415
  6. 0.9209
  7. 0.7533
  8. 0.6306
  9. 0.4930
  10. 0.3180
  11. 0.1204
复 制代码
可以很方便的计算每个主成分所解释的总方差的百分比:
  1. >> percent_explained=100*var/sum(var)

  2. percent_explained =

  3. 37.8699
  4. 13.4886
  5. 12.6831
  6. 10.2324
  7. 8.3698
  8. 7.0062
  9. 5.4783
  10. 3.5338
  11. 1.3378
复 制代码
可见,前面5个主成分所解释的方差占了80%以上。
用帕累托图描述每个注册烦恼所占的百分数:
  1. >> pareto(percent_explained)
  2. >> xlabel('主成分')
  3. >> ylabel('方差解释')
复制代码

有图可以看出,前面3个主成分基本解释了2/3的标准化ratings的总变异性。
(4)第4个输出——Hotelling的T2检验
Hotelling的T2检验统计量是描述每一测量值与数据中心距离的统计量,用它可以找到数据中的极值点:
  1. >> [st,ind]=sort(ts);
  2. >> st=flipud(st);
  3. >> ind=flipud(ind);
  4. >> ex=ind(1);
  5. >> ex=ind(1)

  6. ex =

  7. 213

  8. >> names(ex,:)

  9. ans =

  10. New York, NY
复制代码
说明New York, NY是离数据中心最远的城市!!!!

http://www.matlabsky.com/thread-1213-1-1.html

2010年4月8日星期四

matlab c# 混合编程实例---matlab帮助文档

Deploying a Component Using the Magic Square Example
On this page…

About This Example

Magic Square Example: MATLAB Programmer Tasks

Using the Command Line to Create .NET Components

Magic Square Example: .NET Programmer Tasks
About This Example

This example shows you how to transform a simple M-code function into a deployable MATLAB Builder NE component.

The Magic Square example shows you how to create a .NET component named MagicSquareComp, which contains the magic class and other files needed to deploy your application.

The magicSquareClass wraps a MATLAB function, makesquare, which computes a magic square. A magic square is a matrix containing any number of rows. These rows, added horizontally, vertically, or diagonally, equate to the same value. MATLAB contains a function, magic, that you can use to create magic squares of any dimension.

Note The examples here use the Windows deploytool GUI, a graphical front-end interface to MATLAB Compiler software. For information about how to perform these tasks using the command-line interface to MATLAB Compiler software, see the mcc reference page.

Note If you wish to create a remotable component, and for information about what this entails, see Sharing Components Across Distributed Applications Using .NET Remoting.

Back to Top of Page Back to Top
Magic Square Example: MATLAB Programmer Tasks

The MATLAB programmer usually performs the following tasks.

Key Tasks for the MATLAB Programmer
Task Reference
1. Start the product. Starting the Deployment Tool
2. Prepare to run the example by copying the MATLAB example files into a work folder. Copying the Example Files
3. Test the M-code to ensure it is suitable for deployment. Testing the M-File You Want to Deploy
4. Create a .NET component (encapsulating your M-code in a .NET class) by running the Build function in deploytool. Building Your Component
5. Prepare to run the Packaging Tool by determining what additional files to include with the deployed component. Packaging Your Component (Optional)
6. Copy the output. Copying the Package You Created

Note The MATLAB Builder NE examples are in matlabroot\toolbox\dotnetbuilder\Examples\VS8\NET. This example assumes the work folder is on drive D:.

Starting the Deployment Tool

Access the MATLAB Builder NE product through the Deployment Tool GUI (deploytool) or through the mcc function of the MATLAB Compiler product. deploytool is the GUI front end for mcc, which executes MATLAB Compiler software.

This example uses deploytool. If you want to use mcc, see the mcc reference page for complete reference information.

To start this product:

1.

Start MATLAB.
2.

Type deploytool at the MATLAB command prompt. The deploytool GUI opens.

Copying the Example Files

Prepare to run the example by copying needed files into your work area as follows:

1.

Navigate to matlabroot\toolbox\dotnetbuilder\Examples\VS8\NET\MagicSquareExample.

Tip matlabroot is the MATLAB root folder (where MATLAB is installed). To find the value of this variable on your system, type matlabroot at a MATLAB command prompt.
2.

Copy the MagicSquareExample folder to a work area, for example, D:\dotnetbuilder_examples. Avoid using spaces in your folder names, if possible.
3.

Rename the subfolder MagicSquareExample to magic_square. The example files should now reside in D:\dotnetbuilder_examples\magic_square.
4.

Using a system command prompt, navigate to D:\dotnetbuilder_examples\magic_square by switching to the D: drive and entering cd \dotnetbuilder_examples\magic_square.

Testing the M-File You Want to Deploy

In this example, you test a precreated M-file (magicsquare.m) containing the predefined MATLAB function magic, in order to have a baseline to compare to the results of the function when it is finally wrappered as a deployable .NET component.

1.

Using MATLAB, locate the magicsquare.m file at D:\dotnetbuilder_examples\magic_square\MagicDemoComp. The contents of the file are as follows:

function y = makesquare(x)
%MAKESQUARE Magic square of size x.
% Y = MAKESQUARE(X) returns a magic square of size x.
% This file is used as an example for the MATLAB
% Builder NE product.

% Copyright 2001-2009 The MathWorks, Inc.

y = magic(x);

2.

To run makesquare, ensure that MATLAB can find it. Select File > Set Path in MATLAB to add the D:\dotnetbuilder_examples\magic_square\MagicDemoComp folder to the MATLAB search path.
3.

At the MATLAB command prompt, enter makesquare(5) and view the results. The output should appear as follows:

17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9

About MATLAB Function Signatures. MATLAB supports multiple signatures for function calls.

The generic MATLAB function has the following structure:

function [Out1,Out2,...,varargout]=foo(In1,In2,...,varargin)

To the left of the equal sign, the function specifies a set of explicit and optional return arguments.

To the right of the equal sign, the function lists explicit input arguments followed by one or more optional arguments.

All arguments represent a specific MATLAB type.

When the MATLAB Builder NE product processes your M-code, it creates several overloaded methods that implement the MATLAB functions. Each of these overloaded methods corresponds to a call to the generic MATLAB function with a specific number of input arguments. In addition to these methods, the builder creates another method that defines the return values of the MATLAB function as an input argument. This method simulates the feval external API interface in MATLAB.
Building Your Component

You create a .NET component by using the Deployment Tool GUI to build a .NET class that wraps around the sample M-code discussed in Testing the M-File You Want to Deploy.

Use the following information when creating your component as you work through this example:
Project Name magicSquareComp
Class Name magicSquareClass
File to compile makesquare.m

1.

Create a deployment project. A project is a collection of files you bundle together under a project file name (.prj file) for your convenience in the Deployment Tool. Using a project makes it easy for you to build and run an application many times—effectively testing it—until it is ready for deployment.
1.

Type the name of your project in the Name field.
2.

Enter the location of the project in the Location field. Alternately, navigate to the location.
3.

Select the target for the deployment project from the Target drop-down menu.
4.

Click OK.
2.

On the Build tab, add what you want to compile, and any supporting files, to the project.
1.

Do the following, depending on the type of application you are building:
*

If you are building a COM application or Microsoft® Excel® add-in, click Add files.
*

If you are building a .NET application, click Add class. Type the name of the class in the Class Name field, designated by the letter "c":

For this class, add files you want to compile by clicking Add files. To add another class, click Add class.
2.

Add any supporting files. For example, you can add the following files, as appropriate for your project:
*

Functions called using eval (or variants of eval)
*

Functions not on the MATLAB path
*

Code you want to remain private
*

Code from other programs that you want to compile and link into the main file

If you want to include additional files, in the Shared Resources and Helper Files area, click Add files/directories. Click Open to select the file or files.
3.

When you complete your changes, click the Build button ( ).

How the .NET Builder Creates a Component. To create a component, the builder does the following:

1.

Generates C# code to implement your component

The first step of the build process generates two C# files: a component data file and a component wrapper. The component data file contains static information for the component. The wrapper contains the implementation code for the .NET component and provides a .NET application programming interface (API) for the MATLAB functions you add to the project at design time.
2.

Compiles the C# code and generates /distrib and /src subfolders

The second step of the build process compiles the two C# files produced in step 1, creating a managed assembly for the component.

The MATLAB Builder NE product creates two subfolders under the project folder: project-folder/src and project-folder/distrib. These subfolders contain the following files.

Files in the Project Subfolders
Subfolder Files Description
src ComponentName
_mcc_component_data.cs C# component data file
ClassName1.cs ...
ClassNameN.cs C# wrapper class file
distrib ComponentName.dll .NET component assembly
ComponentName.pdb .NET component debug file (Debug builds only)
ComponentName.xml .NET component XML documentation file
MWArray.xml
component_name.xml
component_name_overview.html Documentation template files. See Using Enhanced XML Documentation Files.

Note When you build your project, you can specify the compilation of a private or shared assembly. A private assembly is copied to an application subfolder and is owned exclusively by the application. A shared assembly usually resides in the Global Assembly Cache, and can be directly referenced by multiple applications.

Packaging Your Component (Optional)

Bundling the .NET component with additional files you can distribute to users is called packaging. You perform this step using the packaging function of deploytool. Alternately, copy the contents of the distrib folder and the MCR Installer to a local folder of your choice. If you are creating a shared component and want to include additional code with the component, you must perform this step.

1.

On the Package tab, add the MATLAB Compiler Runtime (the MCR) by clicking Add MCR.
2.

Next, add others files useful for end users. The readme.txt file contains important information about others files useful for end users. To package additional files or folders, click Add file/directories, select the file or folder you want to package, and click Open.
3.

In the Deployment Tool, click the Packaging button ( ).
4.

After packaging, the package resides in the distrib subfolder. On Windows, the package is a self-extracting executable. On platforms other than Windows, it is a .zip file. Verify that the contents of the distrib folder contains the files you specified.

What Happens in the Packaging Process?. The package process zips the following files into a single self-extracting executable, componentName.exe:

*

componentName.dll
*

componentName.xml
*

componentName.pdb (if the Debug option is selected)
*

MCRInstaller.exe (if the Include MCR option is selected)
*

_install.bat (script run by the self-extracting executable)

How the MCR Is Shared Among Classes. The builder creates a single MCR instance for each MATLAB Builder NE class in an application. This MCR is reused and shared among all subsequent class instances within the component, resulting in more efficient memory usage and eliminating the MCR startup cost in each subsequent class instantiation. All class instances share a single MATLAB workspace and share global variables in the M-files used to build the component.

The following example creates a .NET component called mycomponent containing a single .NET class named myclass with methods foo and bar.

If and when multiple instances of myclass are instantiated in an application, only one MCR is initialized, and it is shared by all instances of myclass.

mcc -B 'dotnet:mycomponent,myclass,2.0,Private,local' foo.m bar.m

Copying the Package You Created

Copy the package that you created from the distrib folder to the local folder of your choice or send them directly to the .NET programmer.

Back to Top of Page Back to Top
Using the Command Line to Create .NET Components

Instead of using the Deployment Tool to create .NET components, you can use the mcc command.

The following sections describe the subset of mcc command options that you need to create .NET components. The sections provide detailed mcc syntax with examples.

To learn more about the mcc command and all of its options, see the MATLAB Compiler documentation.
Command-Line Syntax Description

The following command defines the complete mcc command syntax with all required and optional arguments used to create a .NET component. Brackets indicate optional parts of the syntax.

mcc - W 'dotnet:component_name,class_name, 0.0|2.0, Private|Encryption_Key_Path,local|remote' file1 [file2...fileN][class{class_name:file1 [,file2,...,fileN]},... [-d output_dir_path] -T link:lib

Note For complete information about the mcc command, including the -W option, see mcc in the function reference section of this user's guide.

Using the .NET Bundle Files to Simplify the Command

To simplify the command line used to create .NET components, you can use the .NET Builder bundle file, named dotnet, to make creating .NET components easier. When using this bundle file, you must still pass in the four parts of the -W argument text string, however, you do not have to specify the -T option.

The following example creates a .NET component called mycomponent containing a single .NET class named myclass with methods foo and bar. When used with the -B option, the word dotnet specifies the name of the predefined .NET Builder bundle file.

mcc -B 'dotnet:mycomponent,myclass,2.0,encryption_keyfile_path,local'
foo.m bar.m

In this example, the builder uses the .NET Framework version 2.0 to compile the component into a shared assembly using the key file specified in encryption_keyfile_path to sign the shared component.
Example: Creating a .NET Component Namespace

The following example creates a .NET component from two M-files foo.m and bar.m.

mcc - B 'dotnet:mycompany.mygroup.mycomponent,myclass,0.0,Private,local'
foo.m bar.m

The example creates a .NET component named mycomponent that has the following namespace: mycompany.mygroup. The component contains a single .NET class, myclass, which contains methods foo and bar.

To use myclass, place the following statement in your code:

using mycompany.mygroup;

Example: Adding Multiple Classes to a Component

The following example creates a .NET component that includes more than one class. This example uses the optional class{...} argument to the mcc command.

mcc - B 'dotnet:mycompany.mycomponent,myclass,2.0,Private,local' foo.m bar.m
class{myclass2:foo2.m,bar2.m}

The example creates a .NET component named mycomponent with two classes:

*

myclass has methods foo and bar
*

myclass2 has methods foo2 and bar2

Back to Top of Page Back to Top
Magic Square Example: .NET Programmer Tasks

The following tasks are usually performed by the .NET programmer.

Key Tasks for the .NET Programmer
Task Reference
1. Ensure you have the needed files from the MATLAB programmer before proceeding. Gathering Files Needed for Deployment
2. Use the component in a .NET application. Compile and run the component to ensure it produces the same results as your M-code. Using the Component in an Application
3. Archive and distribute the output to end users. Distributing the Component to End Users
4. Integrate classes generated by the MATLAB Builder NE product into existing .NET applications. Integrating .NET Classes Generated by MATLAB into a .NET Application
5. Verify your .NET application works as expected in your end user's deployment environment. Building and Testing the .NET Application

Gathering Files Needed for Deployment

Before beginning, verify you have access to the following files, created by the MATLAB programmer in Copying the Package You Created. The following files are required to deploy to users who do not have a copy of MATLAB installed:

*

MCR Installer. For locations of all MCR Installers, run the mcrinstaller command.
*

readme.txt

See Packaging Your Component (Optional) for more information about these files. You will also want to communicate the location of the MWArray Class Library Reference. You can also browse to this library from the MATLAB Builder NE help tree (left pane of MATLAB Product Help).

How Component Deployment Works. To deploy the component, run the MCR installer. The installer does the following:

1.

Installs the MCR (if not already installed on the target machine)
2.

Installs the component assembly in the folder from which the installer is run
3.

Copies the MWArray assembly to the Global Assembly Cache (GAC), as part of installing the MCR

Note Since installing the MCR requires write access to the system registry, you must have administrator privileges to run the MCR Installer.

Note On target machines where the MCR Installer is run, the MCR Installer puts the MWArray assembly in installation_folder\toolbox\dotnetbuilder\runtime\architecture
\version_number.

The MCR Installer uses a standard Microsoft installation file that provides the following features:

*

Integrates with Add/Remove Programs in the Control Panel
*

Checks software prerequisites before installation
*

Checks for proper user permissions
*

Rolls back the system to its prior state on installation failure
*

Supports component versioning

Using the Component in an Application

1.

Write source code for an application that uses the .NET component created in Building Your Component.

The C# source code for the sample application for this example is in MagicSquareExample\MagicSquareCSApp\MagicSquareApp.cs.

The program listing is shown here.

Tip Although MATLAB Builder NE generates C# code for the MagicSquare component and the sample application is in C#, applications that use the component do not need to be coded in C#. You can access the component from any CLS-compliant .NET language. For examples, see Sample Applications (Microsoft Visual Basic .NET).

MagicSquareApp.cs

// *******************************************************************************
//
// MagicDemoApp.cs
//
// This file is an example application for the MATLAB Builder NE product.
//
// Copyright 2001-2009 The MathWorks, Inc.
//
// *******************************************************************************

using System;

using MathWorks.MATLAB.NET.Utility;
using MathWorks.MATLAB.NET.Arrays;

using MagicDemoComp;


namespace MathWorks.Demo.MagicSquareApp
{
///
/// The MagicSquareApp demo class computes a magic square of the user-specified size.
///

///
/// args[0] - a positive integer representing the array size.
///

class MagicDemoApp
{
#region MAIN

///
/// The main entry point for the application.
///

[STAThread]
static void Main(string[] args)
{
MWNumericArray arraySize= null;
MWNumericArray magicSquare= null;

try
{
// Get user-specified command line arguments or set default
arraySize= (0 != args.Length) ? System.Double.Parse(args[0]) : 4;

// Create the magic square object
MagicSquare magic= new MagicSquare();

// Compute the magic square and print the result
magicSquare= (MWNumericArray)magic.makesquare((MWArray)arraySize);

Console.WriteLine("Magic square of order {0}\n\n{1}", arraySize, magicSquare);

// Convert the magic square array to a two-dimensional native double array
double[,] nativeArray= (double[,])magicSquare.ToArray(MWArrayComponent.Real);

Console.WriteLine("\nMagic square as native array:\n");

// Display the array elements:
for (int i= 0; i < (int)arraySize; i++)
for (int j= 0; j < (int)arraySize; j++)
Console.WriteLine("Element({0},{1})= {2}", i, j, nativeArray[i,j]);

Console.ReadLine(); // Wait for user to exit application
}

catch(Exception exception)
{
Console.WriteLine("Error: {0}", exception);
}
}
#endregion
}
}

2.

Build the application using Visual Studio® .NET.

Note In the project file for this example, the MWArray assembly and the magic square component assembly have been prereferenced. Any references preceded by an exclamation point require you to remove the reference and rereference the affected assembly.

Note Microsoft .NET Framework version 2.0 is not supported by Visual Studio 2003.
1.

Open the project file for the Magic Square example (MagicSquareCSApp.csproj) in Visual Studio .NET.
2.

If necessary, add a reference to the MWArray component in matlabroot\toolbox\dotnetbuilder\bin\
architecture\framework_version.
3.

If necessary, add a reference to the Magic Square component (MagicSquareComp), which is in the distrib subfolder.

Distributing the Component to End Users

If you bundled the component as a self-extracting executable, paste it in a folder on the development machine and run it. If you are using a .zip file bundled with WinZip, unzip and extract the contents to the development machine.
Integrating .NET Classes Generated by MATLAB into a .NET Application

*

Classes and Methods
*

Component and Class Naming Conventions
*

Versioning
*

Managing Data Conversion Issues with MATLAB Builder NE Data Conversion Classes
*

Automatic Casting to MATLAB Types
*

Adding Fields to Data Structures and Data Structure Arrays
*

About MATLAB Array Indexing
*

Accessing Your Component On Another Computer

Classes and Methods. The builder project contains the files and settings needed by the MATLAB Builder NE product to create a deployable .NET component. A project specifies information about classes and methods, including the MATLAB functions to be included.

The builder transforms MATLAB functions that are specified in the component's project to methods belonging to a managed class.

When creating a component, you must provide one or more class names as well as a component name. The component name also specifies the name of the assembly that implements the component. The class name denotes the name of the class that encapsulates MATLAB functions.

To access the features and operations provided by the MATLAB functions, instantiate the managed class generated by the builder, and then call the methods that encapsulate the MATLAB functions.

Component and Class Naming Conventions. Typically you should specify names for components and classes that will be clear to programmers who use your components. For example, if you are encapsulating many MATLAB functions, it helps to determine a scheme of function categories and to create a separate class for each category. Also, the name of each class should be descriptive of what the class does.

The .NET Framework General Reference recommends the use of Pascal case for capitalizing the names of identifiers of three or more characters. That is, the first letter in the identifier and the first letter of each subsequent concatenated word are capitalized. For example:

MakeSquare

In contrast, MATLAB programmers typically use all lowercase for names of functions. For example:

makesquare

By convention, the MATLAB Builder NE examples use Pascal case.

Valid characters are any alpha or numeric characters, as well as the underscore (_) character.

Versioning. The builder supports the standard versioning capabilities provided by the .NET Framework.

Note You can make side-by-side invocations of multiple versions of a component within the same application only if they access the same version of the MCR.

Managing Data Conversion Issues with MATLAB Builder NE Data Conversion Classes. To support data conversion between managed types and MATLAB types, the builder provides a set of data conversion classes derived from the abstract class, MWArray.

When you invoke a method on a component, the input and output parameters are a derived type of MWArray. To pass parameters, you can either instantiate one of the MWArray subclasses explicitly, or, in many cases, pass the parameters as a managed data type and rely on the implicit data conversion feature of .NET Builder.
Overview of Classes and Methods in the Data Conversion Class Hierarchy.

The data conversion classes are built as a class hierarchy that represents the major MATLAB array types.

Note See Overview for an introduction to the classes and see MWArray Class Library Reference (available online only) for details about this class library.

The root of the hierarchy is the MWArray abstract class. The MWArray class has the following subclasses representing the major MATLAB types: MWNumericArray, MWLogicalArray, MWCharArray, MWCellArray, and MWStructArray.

MWArray and its derived classes provide the following functionality:

*

Constructors and destructors to instantiate and dispose of MATLAB arrays
*

Properties to get and set the array data
*

Indexers to support a subset of MATLAB array indexing
*

Implicit and explicit data conversion operators
*

General methods

Advantage of Using Data Conversion Classes.

The MWArray data conversion classes allow you to pass most native .NET value types as parameters directly without using explicit data conversion. There is an implicit cast operator for most native numeric and string types that will convert the native type to the appropriate MATLAB array.

Automatic Casting to MATLAB Types.

Note Because the conversion process is automatic (in most cases), you do not need to understand the conversion process to pass and return arguments with MATLAB Builder NE components.

In most instances, if a native .NET primitive or array is used as an input parameter in a C# program, the builder transparently converts it to an instance of the appropriate MWArray class before it is passed on to the component method. The builder can convert most CLS-compliant string, numeric type, or multidimensional array of these types to an appropriate MWArray type.

Note This conversion is transparent in C# applications, but might require an explicit casting operator in other languages, for example, op_implicit in Visual Basic®.

Here is an example. Consider the .NET statement:

result = theFourier.plotfft(3, data, interval);

In this statement the third argument, namely interval, is of the .NET native type System.Double. The builder casts this argument to a MATLAB 1-by-1 double MWNumericArray type (which is a wrapper class containing a MATLAB double array).

See Data Conversion Rules for a list of all the data types that are supported along with their equivalent types in the MATLAB product.

Note There are some data types commonly used in the MATLAB product that are not available as native .NET types. Examples are cell arrays, structure arrays, and arrays of complex numbers. Represent these array types as instances of MWCellArray, MWStructArray, and MWNumericArray, respectively.

Adding Fields to Data Structures and Data Structure Arrays. When adding fields to data structures and data structure arrays, do so using standard programming techniques. Do not use the set command as a shortcut.

For examples of how to correctly add fields to data structures and data structure arrays, see the programming examples in Sample Applications (C#) and Sample Applications (Microsoft Visual Basic .NET).

About MATLAB Array Indexing. .NET Builder provides indexers to support a subset of MATLAB array indexing.

Note If each element in a large array returned by a .NET Builder component is to be indexed, the returned MATLAB array should first be converted to a native array using the toArray() method. This results in much better performance.

Don't keep the array in MATLAB type; convert it to a native array first. See Getting Started for an example of native type conversion.

Accessing Your Component On Another Computer. To implement your .NET component on a computer other than the one on which it was built:

1.

If the component is not already installed on the machine where you want to develop your application, run the self-extracting executable that you created in Deploying a Component Using the Magic Square Example.

This step is not necessary if you are developing your application on the same machine where you created the .NET component.
2.

Reference the .NET component in your Microsoft® Visual Studio® project or from the command line of a CLS-compliant compiler.

You must also add a reference to the MWArray component in matlabroot\toolbox\dotnetbuilder\bin\architecture\framework_version.
3.

Instantiate the generated .NET Builder classes and call the class methods as you would with any .NET class. To marshal data between the native .NET types and the MATLAB array type, you need to use either the MWArray data conversion classes or the MWArray native API. See MWArray Class Library Reference (available online only) for details about the MWArray API for this class library.

Building and Testing the .NET Application

1.

Build and test the .NET application as you would any application.
2.

Create an application installation package for end users that includes the files required for the .NET Builder components that encapsulate the MATLAB functions.

浏览统计