Matlab数据库编程指南-Godman
- 格式:doc
- 大小:60.50 KB
- 文档页数:10
MATLAB入门指南MATLAB是一款功能强大的数值计算软件和编程环境,广泛应用于科学、工程和数据分析领域。
本文将为初学者提供一份MATLAB入门指南,以帮助他们快速掌握基本概念、使用技巧和常见功能。
第一部分:MATLAB基础1. MATLAB的介绍MATLAB是由MathWorks开发的高级编程语言和环境,其主要用于数值计算、数据可视化和算法开发。
它与其他编程语言相比,有着简单易学的语法和丰富的内置函数库。
2. MATLAB的安装与设置在使用MATLAB之前,您需要先下载和安装MATLAB软件。
安装过程通常是简单的,只需按照提示一步一步执行即可。
安装完成后,您可以根据需要进行一些个性化设置,如选择默认工作目录和字体大小。
3. MATLAB的基本命令和运算符MATLAB的基本命令和运算符与其他编程语言类似,包括数学运算符(加减乘除、幂运算等)、逻辑运算符(与或非等)和比较运算符(等于、大于、小于等)。
您可以使用MATLAB作为计算器来进行简单的数学计算,如计算平方根、三角函数等。
4. MATLAB的变量和数据类型在MATLAB中,您可以使用变量来存储和操作数据。
MATLAB支持多种数据类型,包括数值、字符、逻辑和结构等。
您可以使用赋值语句将数据存储在变量中,并使用变量进行计算和操作。
5. MATLAB的数组和矩阵操作MATLAB以矩阵为基础进行计算,因此对于初学者来说,了解如何创建、操作和计算矩阵是至关重要的。
您可以使用MATLAB提供的函数来创建矩阵,并使用索引和运算符对矩阵进行操作。
第二部分:MATLAB编程和算法1. MATLAB的脚本文件和函数MATLAB提供了编写脚本文件和函数的能力,以便在单个文件中组织代码。
您可以使用脚本文件来一次性执行一系列MATLAB命令,而函数则可以封装一段可重复使用的代码块。
2. MATLAB控制结构MATLAB提供了多种控制结构,如条件语句(if-else)、循环语句(for、while)和跳转语句(break、continue)。
在MATLAB中,可以使用内置的Database Toolbox进行数据库编程。
以下是一些基本步骤,以帮助您开始使用MATLAB进行数据库编程。
1. 连接到数据库使用Database Toolbox提供的函数,可以连接到各种类型的数据库,例如MySQL、Oracle、SQL Server等。
例如,要连接到MySQL 数据库,可以使用以下代码:```matlabconn = database('username','password','database_name','host_name','port');```其中,username和password是数据库的用户名和密码,database_name是数据库的名称,host_name是数据库的主机名,port 是数据库的端口号。
2. 执行SQL查询连接到数据库后,可以使用SQL查询语句执行各种操作,例如SELECT、INSERT、UPDATE、DELETE等。
例如,要查询一个名为table_name的表中的所有数据,可以使用以下代码:```matlabsql_query = 'SELECT * FROM table_name';result = exec(conn, sql_query);```其中,exec函数执行SQL查询并返回结果。
3. 处理查询结果查询结果可以以表格或元数据的形式返回。
可以使用MATLAB 内置的函数处理查询结果,例如将结果保存到变量中、显示结果等。
例如,要将查询结果保存到名为result的变量中,可以使用以下代码:```matlabresult = fetch(result);```其中,fetch函数将查询结果保存到变量中。
4. 关闭连接在完成所有操作后,应该关闭与数据库的连接。
可以使用close 函数关闭连接,例如:```matlabclose(conn);```以上是MATLAB数据库编程的基本步骤。
简单易学的MATLAB编程入门指南MATLAB是一种强大而广泛应用于科学计算与工程开发中的高级编程语言和环境。
它可以帮助工程师、科学家和学生快速、高效地进行数据分析、算法开发和可视化。
本文将为初学者提供一份简单易学的MATLAB编程入门指南,帮助他们快速上手并应用于实践。
第一章:MATLAB的安装与基本概念在开始学习MATLAB之前,首先需要正确安装MATLAB软件。
MATLAB官方网站提供了支持不同操作系统的安装程序,用户可以根据自己的需要进行下载。
安装完成后,打开软件,熟悉界面布局与基本概念,如命令窗口、编辑器、工程管理器等。
第二章:MATLAB基本语法与数据类型MATLAB基于矩阵与向量运算,因此掌握基本的数据类型与运算是编写MATLAB程序的基础。
本章将介绍MATLAB的基本语法规则、变量与常量的定义、数学运算、逻辑运算等知识点,并通过实例进行演示。
第三章:MATLAB的函数与脚本MATLAB中的函数与脚本是编写程序的重要组成部分。
本章将详细介绍函数与脚本的定义与使用方法,并讲解函数与脚本之间的区别。
同时,还会介绍常用的MATLAB内置函数,如plot、sqrt、sin等,以及如何自定义函数。
第四章:MATLAB的矩阵与向量操作矩阵与向量是MATLAB最常用的数据结构,也是实现数据分析与算法开发的核心。
本章将介绍如何创建矩阵与向量、对矩阵与向量进行计算与操作,并涉及常见的矩阵运算、线性代数运算、数据筛选与排序等技巧。
第五章:MATLAB的数据可视化MATLAB提供了丰富的绘图函数和工具箱,可以方便地进行数据可视化与图形展示。
本章将介绍如何使用MATLAB进行简单的二维和三维绘图,包括折线图、散点图、柱状图、饼图、曲面绘制等。
同时,还会介绍如何设置图形属性、添加图例和坐标轴标签等。
第六章:MATLAB的数据分析与统计MATLAB提供了丰富的数据分析与统计函数,可以方便地进行数据预处理、特征提取和模型评估等工作。
MATLAB编程基础入门MATLAB是一种常用于科学计算和数据分析的高级编程语言和环境。
它提供了丰富的工具集,使得处理数值计算、绘制图形以及实现算法变得更加便捷。
本文将为初学者介绍MATLAB的基础知识和编程技巧,以帮助读者快速入门。
1. MATLAB的安装和启动首先,我们需要到MathWorks官网上下载并安装MATLAB。
安装完成后,双击MATLAB图标即可启动软件。
MATLAB的主界面分为命令窗口、编辑器和工作空间等几个主要部分,用户可以通过这些界面进行编程和运行程序。
2. MATLAB的基本语法MATLAB的基本语法与其他编程语言有所不同。
在MATLAB中,不需要声明变量的类型,只需要直接给变量赋值即可。
例如:```a = 10;b = 3.14;c = 'Hello, MATLAB!';```MATLAB中还有一些特殊变量和函数,比如`pi`表示圆周率,`sin`表示正弦函数。
使用这些特殊变量和函数可以实现更加高效的数值计算和数据处理。
3. MATLAB的基本操作MATLAB提供了丰富的操作符和函数,可以用于数值计算、矩阵运算、图形绘制等。
下面是一些常用操作的示例:3.1 数值计算```a = 5;b = 3;c = a + b; % 加法运算d = a * b; % 乘法运算e = sqrt(a); % 开方运算```3.2 矩阵运算```A = [1 2 3; 4 5 6; 7 8 9]; % 创建一个3x3的矩阵B = [10 11 12; 13 14 15; 16 17 18];C = A + B; % 矩阵相加D = A * B; % 矩阵相乘```3.3 图形绘制```x = linspace(0, 2*pi, 100); % 在0到2π之间生成100个等间隔的点y = sin(x);plot(x, y); % 绘制正弦函数图像xlabel('x'); % 设置x轴标签ylabel('y'); % 设置y轴标签title('Sin Function'); % 设置图像标题```4. MATLAB的程序控制MATLAB提供了丰富的控制结构,可以用于实现条件判断和循环等功能。
Matlab入门教程(很齐全)嘿,伙计们!今天我要给大家介绍一个超级好玩的东西——Matlab入门教程!这可是一个让你轻松掌握Matlab的绝佳机会,不管你是编程小白还是有经验的小伙伴,都能在这里找到属于自己的一片天地。
不多说了,让我们开始吧!我们来了解一下Matlab是什么。
Matlab是一种高级数学软件,它可以帮助你进行各种复杂的计算和数据处理。
它的特点是界面友好,操作简单,而且功能强大。
无论你是学数学、物理、工程还是计算机专业的学生,都可以用Matlab来提高自己的技能。
我们该如何开始学习Matlab呢?你需要安装Matlab软件。
这个过程非常简单,只需要按照提示一步步操作就可以了。
安装完成后,我们就可以开始学习了。
在Matlab中,有很多基本的操作和函数可以使用。
比如,我们可以用变量来存储数据,用算术运算符来进行简单的计算,用逻辑运算符来进行条件判断等等。
这些都是Matlab的基本操作,掌握了这些,你就可以开始进行更复杂的计算了。
除了基本操作之外,Matlab还有很多强大的函数可以使用。
这些函数可以帮助你完成各种各样的任务,比如绘制图形、分析数据、解决方程等等。
学会使用这些函数,可以让你的计算变得更加高效和准确。
学习Matlab并不是一蹴而就的事情。
你需要不断地练习和实践,才能真正掌握它。
我建议你可以找一些实际的问题来尝试解决,这样既能巩固所学的知识,又能提高自己的动手能力。
Matlab是一个非常有趣且实用的工具。
只要你肯下功夫去学习,相信你一定能够掌握它。
今天的教程就到这里啦!希望大家能够喜欢这个教程,也希望大家能够在学习过程中取得好成绩!下次再见啦!。
MATLAB编程基础指南第一章:MATLAB简介MATLAB是一种高级的数值计算和科学编程语言,广泛应用于工程、科学、统计学等领域。
本章将介绍MATLAB的起源、特点以及适用范围,并指引读者安装和启动MATLAB。
1.1 MATLAB的起源1.1.1 发展背景1.1.2 MATLAB的定义和功能1.1.3 MATLAB的优势和劣势1.2 MATLAB适用领域1.2.1 工程应用1.2.2 科学研究1.2.3 统计分析1.2.4 数据可视化1.3 安装和启动MATLAB1.3.1 系统要求1.3.2 安装步骤1.3.3 启动和关闭MATLAB第二章:MATLAB基本语法本章将介绍MATLAB的基本语法规则,包括变量的定义与赋值、矩阵与数组的操作、条件语句和循环语句等。
通过学习本章内容,读者将了解如何编写简单的MATLAB程序。
2.1 变量和赋值2.1.1 变量的命名规则2.1.2 变量类型和初始化2.1.3 变量的赋值和修改2.2 矩阵和数组操作2.2.1 矩阵的定义和索引2.2.2 矩阵运算和元素操作2.2.3 数组的创建和变形2.3 条件语句2.3.1 if语句2.3.2 switch语句2.4 循环语句2.4.1 for循环2.4.2 while循环第三章:MATLAB函数与脚本文件本章将介绍如何定义和使用MATLAB函数,并探讨函数和脚本文件的区别与联系。
读者将学会如何编写自定义函数,并将其与其他MATLAB功能进行结合。
3.1 函数的定义与调用3.1.1 函数的结构3.1.2 函数的调用和返回值3.2 MATLAB预定义函数3.2.1 常用数学函数3.2.2 统计函数和概率分布3.2.3 信号处理函数3.3 脚本文件的编写3.3.1 创建脚本文件3.3.2 脚本文件的执行顺序3.3.3 脚本文件与函数的关系第四章:数据处理与分析本章将介绍MATLAB在数据处理与分析方面的丰富功能,包括数据导入与导出、数据可视化、统计分析等。
MATLAB编程基础教程在计算机科学和工程领域,MATLAB(Matrix Laboratory)是一个广泛用于数值分析和科学计算的高级编程语言和环境。
它的强大功能和简洁的语法使得它成为许多科学家和工程师的首选工具。
本文将介绍MATLAB的基础知识,帮助读者快速入门并进行简单的编程。
1. MATLAB的安装与环境配置首先,我们需要下载并安装MATLAB软件。
MATLAB可以在官方网站上免费获取到,并提供不同的版本供选择。
安装程序非常简单,只需按照向导的指示进行操作即可完成安装。
安装完成后,我们需要进行一些环境配置。
首先启动MATLAB软件,然后选择合适的工作目录。
工作目录是我们存储和管理MATLAB文件的地方。
选择一个方便和易于查找的目录,并将其设置为工作目录。
接下来,我们还可以对编辑器的外观和功能进行自定义设置,以适应个人的需要。
2. MATLAB的基本语法和语句在MATLAB中,所有的操作都是通过输入命令来完成的。
MATLAB的命令由一个或多个关键字组成,可以用于执行各种操作,包括数值计算、数据可视化和文件处理等。
下面是一些常用的MATLAB命令示例:- disp('Hello, world!'):显示一个文本消息- a = 1 + 2:将1与2相加,并将结果保存到变量a中- b = sqrt(9):计算9的平方根,并将结果保存到变量b中- c = linspace(1, 10, 10):生成一个由1到10的10个等间距数字组成的向量,并将结果保存到变量c中MATLAB还提供了丰富的数学函数和运算符,可以进行各种数值计算操作。
例如,可以使用'+'运算符进行加法运算,使用'-'运算符进行减法运算,使用'*'运算符进行乘法运算,使用'/'运算符进行除法运算等。
此外,MATLAB还提供了一些特殊的函数,如sin、cos、exp、log等,用于实现各种数学运算。
MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics.If you have any feedback please feel free to reach me at @the_ozzinator,or osvaldo.t.mendoza@.%% Code sections start with two percent signs. Section titles go on the same line.% Comments start with a percent sign.%{Multi line comments looksomethinglikethis%}% commands can span multiple lines, using '...':a = 1+2+ ...+4% commands can be passed to the operating system!ping who% Displays all variables in memorywhos% Displays all variables in memory, with their typesclear% Erases all your variables from memoryclear('A') % Erases a particular variableopenvar('A') % Open variable in variable editorclc% Erases the writing on your Command Windowdiary% Toggle writing Command Window text to filectrl-c % Abort current computationedit('myfunction.m') % Open function/script in editortype('myfunction.m') % Print the source of function/script to Command Windowprofile on% turns on the code profilerprofile off% turns off the code profilerprofile viewer % Open profilerhelp command % Displays documentation for command in Command Windowdoc command % Displays documentation for command in Help Windowlookfor command % Searches for command in the first commented line of all functionslookfor command -all% searches for command in all functions% Output formattingformat short % 4 decimals in a floating numberformat long % 15 decimalsformat bank % only two digits after decimal point - for financial calculationsfprintf('text') % print "text" to the screendisp('text') % print "text" to the screen% Variables & ExpressionsmyVariable = 4% Notice Workspace pane shows newly created variable myVariable = 4; % Semi colon suppresses output to the Command Window4+6% ans = 108* myVariable % ans = 322^3% ans = 8a = 2;b = 3;c = exp(a)*sin(pi/2) % c = 7.3891% Calling functions can be done in either of two ways:% Standard function syntax:load('myFile.mat', 'y') % arguments within parentheses, separated by commas % Command syntax:load myFile.mat y % no parentheses, and spaces instead of commas% Note the lack of quote marks in command form: inputs are always passed as % literal text - cannot pass variable values. Also, can't receive output: [V,D] = eig(A); % this has no equivalent in command form[~,D] = eig(A); % if you only want D and not V% Logicals1>5% ans = 010>=10% ans = 13~=4% Not equal to -> ans = 13==3% equal to -> ans = 13>1&&4>1% AND -> ans = 13>1||4>1% OR -> ans = 1~1 % NOT -> ans = 0% Logicals can be applied to matrices:A >5% for each element, if condition is true, that element is 1 in returned matrix A( A >5 )% returns a vector containing the elements in A for which condition is true% Stringsa = 'MyString'length(a) % ans = 8a(2) % ans = y[a,a] % ans = MyStringMyString% Cellsa = {'one', 'two', 'three'}a(1) % ans = 'one' - returns a cellchar(a(1)) % ans = one - returns a string% StructuresA.b = {'one','two'};A.c = [12];A.d.e = false;% Vectorsx = [4325371]x(2) % ans = 32, indices in Matlab start 1, not 0x(2:3) % ans = 32 53x(2:end) % ans = 32 53 7 1x = [4; 32; 53; 7; 1] % Column vectorx = [1:10] % x = 1 2 3 4 5 6 7 8 9 10x = [1:2:10] % Increment by 2, i.e. x = 1 3 5 7 9% MatricesA = [123; 456; 789]% Rows are separated by a semicolon; elements are separated with space or comma % A =% 1 2 3% 4 5 6% 7 8 9A(2,3) % ans = 6, A(row, column)A(6) % ans = 8% (implicitly concatenates columns into vector, then indexes into that)A(2,3) = 42% Update row 2 col 3 with 42% A =% 1 2 3% 4 5 42% 7 8 9A(2:3,2:3) % Creates a new matrix from the old one%ans =% 5 42% 8 9A(:,1) % All rows in column 1%ans =% 1% 4% 7A(1,:) % All columns in row 1%ans =% 1 2 3[A ; A] % Concatenation of matrices (vertically)%ans =% 1 2 3% 4 5 42% 7 8 9% 1 2 3% 4 5 42% 7 8 9% this is the same asvertcat(A,A);[A , A] % Concatenation of matrices (horizontally)%ans =% 1 2 3 1 2 3% 4 5 42 4 5 42% 7 8 9 7 8 9% this is the same ashorzcat(A,A);A(:, [312]) % Rearrange the columns of original matrix%ans =% 3 1 2% 42 4 5% 9 7 8size(A) % ans = 3 3A(1, :) =[] % Delete the first row of the matrixA(:, 1) =[] % Delete the first column of the matrixtranspose(A) % Transpose the matrix, which is the same as:A onectranspose(A) % Hermitian transpose the matrix% (the transpose, followed by taking complex conjugate of each element)A'% Concise version of complex transposeA.'% Concise version of transpose (without taking complex conjugate)% Element by Element Arithmetic vs. Matrix Arithmetic% On their own, the arithmetic operators act on whole matrices. When preceded % by a period, they act on each element instead. For example:A *B % Matrix multiplicationA .*B % Multiple each element in A by its corresponding element in B% There are several pairs of functions, where one acts on each element, and % the other (whose name ends in m) acts on the whole matrix.exp(A) % exponentiate each elementexpm(A) % calculate the matrix exponentialsqrt(A) % take the square root of each elementsqrtm(A) % find the matrix whose square is A% Plottingx = 0:.10:2*pi; % Creates a vector that starts at 0 and ends at 2*pi with increments of .1y = sin(x);plot(x,y)xlabel('x axis')ylabel('y axis')title('Plot of y = sin(x)')axis([02*pi -11]) % x range from 0 to 2*pi, y range from -1 to 1plot(x,y1,'-',x,y2,'--',x,y3,':') % For multiple functions on one plot legend('Line 1 label', 'Line 2 label') % Label curves with a legend% Alternative method to plot multiple functions in one plot.% while 'hold' is on, commands add to existing graph rather than replacing it plot(x, y)holdonplot(x, z)holdoffloglog(x, y) % A log-log plotsemilogx(x, y) % A plot with logarithmic x-axissemilogy(x, y) % A plot with logarithmic y-axisfplot (@(x) x^2, [2,5]) % plot the function x^2 from x=2 to x=5gridon% Show grid; turn off with 'grid off'axissquare% Makes the current axes region squareaxis equal % Set aspect ratio so data units are the same in every directionscatter(x, y); % Scatter-plothist(x); % Histogramstem(x); % Plot values as stems, useful for displaying discrete databar(x); % Plot bar graphz = sin(x);plot3(x,y,z); % 3D line plotpcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value contour(A) % Contour plot of matrixmesh(A) % Plot as a mesh surfaceh = figure% Create new figure object, with handle hfigure(h) % Makes the figure corresponding to handle h the current figure close(h) % close figure with handle hclose all% close all open figure windowsclose% close current figure windowshg % bring an existing graphics window forward, or create new one if needed clf clear% clear current figure window, and reset most figure properties% Properties can be set and changed through a figure handle.% You can save a handle to a figure when you create it.% The function get returns a handle to the current figureh = plot(x, y); % you can save a handle to a figure when you create itset(h, 'Color', 'r')% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' blackset(h, 'LineStyle', '--')% '--' is solid line, '---' dashed, ':' dotted, '-.' dash-dot, 'none' is no line get(h, 'LineStyle')% The function gca returns a handle to the axes for the current figureset(gca, 'XDir', 'reverse'); % reverse the direction of the x-axis% To create a figure that contains several axes in tiled positions, use subplot subplot(2,3,1); % select the first position in a 2-by-3 grid of subplotsplot(x1); title('First Plot') % plot something in this positionsubplot(2,3,2); % select second position in the gridplot(x2); title('Second Plot') % plot something there% To use functions or scripts, they must be on your path or current directory path% display current pathaddpath /path/to/dir% add to pathrmpath /path/to/dir% remove from pathcd /path/to/move/into % change directory% Variables can be saved to .mat filessave('myFileName.mat') % Save the variables in your Workspaceload('myFileName.mat') % Load saved variables into Workspace% M-file Scripts% A script file is an external file that contains a sequence of statements.% They let you avoid repeatedly typing the same code in the Command Window % Have .m extensions% M-file Functions% Like scripts, and have the same .m extension% But can accept input arguments and return an output% Also, they have their own workspace (ie. different variable scope).% Function name should match file name (so save this example as double_input.m). % 'help double_input.m' returns the comments under line beginning function function output = double_input(x)%double_input(x) returns twice the value of xoutput = 2*x;enddouble_input(6) % ans = 12% You can also have subfunctions and nested functions.% Subfunctions are in the same file as the primary function, and can only be % called by functions in the file. Nested functions are defined within another % functions, and have access to both its workspace and their own workspace.% If you want to create a function without creating a new file you can use an % anonymous function. Useful when quickly defining a function to pass to% another function (eg. plot with fplot, evaluate an indefinite integral% with quad, find roots with fzero, or find minimum with fminsearch).% Example that returns the square of it's input, assigned to the handle sqr: sqr = @(x) x.^2;sqr(10) % ans = 100doc function_handle % find out more% User inputa = input('Enter the value: ')% Stops execution of file and gives control to the keyboard: user can examine % or change variables. Type 'return' to continue execution, or 'dbquit' to exit keyboard% Reading in data (also xlsread/importdata/imread for excel/CSV/image files) fopen(filename)% Outputdisp(a) % Print out the value of variable adisp('Hello World') % Print out a stringfprintf% Print to Command Window with more control% Conditional statements (the parentheses are optional, but good style)if (a >15)disp('Greater than 15')elseif (a ==23)disp('a is 23')elsedisp('neither condition met')end% Looping% NB. looping over elements of a vector/matrix is slow!% Where possible, use functions that act on whole vector/matrix at oncefor k = 1:5disp(k)endk = 0;while (k <5)k = k +1;end% Timing code execution: 'toc' prints the time since 'tic' was calledticA = rand(1000);A*A*A*A*A*A*A;toc% Connecting to a MySQL Databasedbname = 'database_name';username = 'root';password = 'root';driver = 'com.mysql.jdbc.Driver';dburl = ['jdbc:mysql://localhost:8889/' dbname];javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depends on version, download available at /downloads/connector/j/conn = database(dbname, username, password, driver, dburl);sql = ['SELECT * from table_name where id = 22'] % Example sql statementa = fetch(conn, sql) %a will contain your data% Common math functionssin(x)cos(x)tan(x)asin(x)acos(x)atan(x)exp(x)sqrt(x)log(x)log10(x)abs(x) %If x is complex, returns magnitudemin(x)max(x)ceil(x)floor(x)round(x)rem(x)rand% Uniformly distributed pseudorandom numbersrandi % Uniformly distributed pseudorandom integersrandn% Normally distributed pseudorandom numbers%Complex math operationsabs(x) % Magnitude of complex variable xphase(x) % Phase (or angle) of complex variable xreal(x) % Returns the real part of x (i.e returns a if x = a +jb)imag(x) % Returns the imaginary part of x (i.e returns b if x = a+jb)conj(x) % Returns the complex conjugate% Common constantspiNaNinf% Solving matrix equations (if no solution, returns a least squares solution) % The \ and / operators are equivalent to the functions mldivide and mrdivide x=A\b % Solves Ax=b. Faster and more numerically accurate than using inv(A)*b. x=b/A % Solves xA=binv(A) % calculate the inverse matrixpinv(A) % calculate the pseudo-inverse% Common matrix functionszeros(m,n) % m x n matrix of 0'sones(m,n) % m x n matrix of 1'sdiag(A) % Extracts the diagonal elements of a matrix Adiag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhereeye(m,n) % Identity matrixlinspace(x1, x2, n) % Return n equally spaced points, with min x1 and max x2 inv(A) % Inverse of matrix Adet(A) % Determinant of Aeig(A) % Eigenvalues and eigenvectors of Atrace(A) % Trace of matrix - equivalent to sum(diag(A))isempty(A) % Tests if array is emptyall(A) % Tests if all elements are nonzero or trueany(A) % Tests if any elements are nonzero or trueisequal(A, B) % Tests equality of two arraysnumel(A) % Number of elements in matrixtriu(x) % Returns the upper triangular part of xtril(x) % Returns the lower triangular part of xcross(A,B) % Returns the cross product of the vectors A and Bdot(A,B) % Returns scalar product of two vectors (must have the same length) transpose(A) % Returns the transpose of Afliplr(A) % Flip matrix left to rightflipud(A) % Flip matrix up to down% Matrix Factorisations[L, U, P] = lu(A) % LU decomposition: PA = LU,L is lower triangular, U is upper triangular, P is permutation matrix[P, D] = eig(A) % eigen-decomposition: AP = PD, P's columns are eigenvectors and D's diagonals are eigenvalues[U,S,V] = svd(X) % SVD: XV = US, U and V are unitary matrices, S has non-negative diagonal elements in decreasing order% Common vector functionsmax% largest componentmin% smallest componentlength% length of a vectorsort% sort in ascending ordersum% sum of elementsprod% product of elementsmode% modal valuemedian% median valuemean% mean valuestd% standard deviationperms(x) % list all permutations of elements of xfind(x) % Finds all non-zero elements of x and returns their indexes, can use comparison operators,% i.e. find( x == 3 ) returns indexes of elements that are equal to 3% i.e. find( x >= 3 ) returns indexes of elements greater than or equal to 3% Classes% Matlab can support object-oriented programming.% Classes must be put in a file of the class name with a .m extension.% To begin, we create a simple class to store GPS waypoints.% Begin WaypointClass.mclassdef WaypointClass% The class name.properties% The properties of the class behave like Structureslatitudelongitudeendmethods% This method that has the same name of the class is the constructor. function obj = WaypointClass(lat, lon)titude = lat;obj.longitude = lon;end% Other functions that use the Waypoint objectfunction r = multiplyLatBy(obj, n)r = n*[titude];end% If we want to add two Waypoint objects together without calling% a special function we can overload Matlab's arithmetic like so:function r = plus(o1,o2)r = WaypointClass([titude] +[titude], ...[o1.longitude]+[o2.longitude]);endendend% End WaypointClass.m% We can create an object of the class using the constructora = WaypointClass(45.0, 45.0)% Class properties behave exactly like Matlab Structures.titude = 70.0a.longitude = 25.0% Methods can be called in the same way as functionsans = multiplyLatBy(a,3)% The method can also be called using dot notation. In this case, the object % does not need to be passed to the method.ans = a.multiplyLatBy(a,1/3)% Matlab functions can be overloaded to handle objects.% In the method above, we have overloaded how Matlab handles% the addition of two Waypoint objects.b = WaypointClass(15.0, 32.0)c = a + b。
Matlab数据库编程指南-GodmanMatlab与数据库链接有三种方法,本文只讲述其中以ODBC的方式进行链接。
本文件包含四部分,其中第三部分为我自己写的一些数据库函数操作的函数,第四部分为网上的一些资料。
如有疑问可以邮件联系**************Godman 2009.3.30 晚Good Luck!第一部分:读取数据其相关信息查看1.配置数据源(1).“控制面板”----“管理工具”——“数据源(ODBC)”——“添加”——“创建数据源名称和选择数据库文件”。
具体操作见“配置数据源.gif”(2).采用修改注册表,自动配置数据源。
DB_path='D:\Program Files\MATLAB71\work\StuSystem.mdb';DB_sourcename='Godman';LinkDB(DB_path,DB_sourcename,1);(LinkDB为自编函数)2.建立链接对象——database调用格式:conna=database(‘datasourcename’,’username’,’password’);如conna=database('SampleDB','','');其中SampleDB为上文中创建的数据源名称,当默认情况下,数据库文件的username和password为空。
3.建立并打开游标——exec调用格式:curs=exec(conna,'sqlquery');如curs=exec(conna,'select * from database')其中conna为上文中链接对象,select * from database表示从表database中选择所有的数据.4.把数据库中的数据读取到Matlab中——fetch调用格式:curs=fetch(curs,RowLimit);Data=curs.Data;%把读取到的数据用变量Data保存.如curs=fetch(curs);把所有的数据一次全部读取到Matlab中,RowLimit为每次读取的数据参数的行数,默认为全部读取,但是全部读取会很费时间(和计算机性能很大关系)。
上述四点是matlab从数据库文件中读取数据到matlab中的基本步骤。
5.数据返回类型从数据库中读取数据到matlab有三种数据类型(默认为元胞类型cellarray),分别为元胞类型(cellarray),数字型(numeric),结构型(structure)。
可以在链接数据库之前通过setdbprefs 函数来进行设置。
如果数据库文件中全部是数值型数据时最好采用numeric型的数据,这样可以使得读取速度大幅提高,特别是在大型数据读取时非常明显。
我曾经从数据库中读取过100万个数据,用cellarray时用了16s,但是用numeric时却只用了8s,速度提高很大啊,对电脑配置不好的来说,很有帮助的。
(还有我的电脑很烂,1.3GHz,384M内存,可能让大家见笑了…….)调用格式:setdbprefs(‘datareturnformat’,’numric’)6.养成良好习惯,随手关闭链接对象和游标——close当不再使用数据库的链接对象时要及时关闭,这样才能及时的释放出内存,而且每次链接后所需要的内存量是非常大的,要是不及时关闭的话对后续计算的影响将非常非常的大。
( 针对烂机子而言,要是你的电脑超强也无所谓的…..)调用格式:close(curs)close(conna)7.查看数据相关信息Rows-查看数据行数调用格式:numrows=rows(curs)Cols——查看数据列数调用格式:numcols=cols(curs)Attr——查看数据属性调用格式:attribute=attr(curs)第二部分:把数据写入到数据库中8.添加数据到表中——insert函数调用格式:insert(conna,’tab’,colnames,exdata)conna——链接对象tab——数据库文件的表名colnames——数据库表的列名exdata——matlab变量如:insert(conna,'try',{'a1', 'a2'},[45 65])commit(conna)%确认数据更改9.更新数据库中的数据——update调用格式:update(conna,’tab’,colnames,exdata,’whereclause’)conna——链接对象tab——数据库文件的表名colnames——数据库表的列名exdata——matlab变量whereclause——SQL的where字句如:update(conna,'try',{'a1', 'a2'},[45 65],’where XX=’XX’’) commit(conna)%确认数据更改10.建立新表——exec,creat table调用格式:conna=database('SampleDB','','');exec(conna,['create table Table(name string,age int)']);close(conna);Table——表名name,age——字段名以上部分是从董振海写的《精通MATLAB7编程与数据库应用》中根据我使用database toolbox的经验摘抄的,在此向作者致谢。
第三部分:自己写的相关函数下面是我在matlab的数据库分析项目的过程中自己写的和用到的关于数据库操作的相关函数的介绍:11.把数据写入到txt文件中.调用格式:data=rand(100,100);dlmwrite('data.txt',data,'delimiter',' ','newline','pc');由于matlab的数据类型默认为双精度的,写入到txt中也是双精度的,此时可以用下面操作来减少有效位数从而减小文件大小。
data=fix(10000*data)/10000;这样保存的txt文件要更小一些.12.把字符串分隔为cell数据——StrSpliteToCell调用格式:StrSpliteToCell(Str1,Str2)Str1为字符串源,str2为分隔号如:DataPath ='D:\Program Files\MATLAB71\work\data.txt'Str='\'StrSpliteToCell(DataPath, Str)ans ='D:' 'Program Files' 'MATLAB71' 'work' 'data.txt'13.cell数据用字符分隔——CellStrJoinWithSeparatora={'D:''Program Files''MATLAB71''work''data.txt'}Str=CellStrJoinWithSeparator(a,'\')Str =Message: ''ErrNum: 0ans: 'D:\Program Files\MATLAB71\work\data.txt'14.把txt文件中的数据写到数据库中由于matlab直接向数据库中保存数据时非常非常的费时,曾经用matlab直接向数据库中写数据时,100万个数据运行了20多分钟还没完,等的太久了就结束了……..所以想到了先把数据保存为txt,再从txt写到数据库文件中,这样这样做的时间花费相对直接写来说几乎可以忽略了把上面的data.txt中的数据写到数据库文件中conna=database('SampleDB','','');DataPath='D:\Program Files\MATLAB71\work\data.txt' f=CreateSchema(DataPath)Txt2Access(conna,DataPath)close(conna)CreateSchema.m是一个写配置文件的函数Txt2Access.m是把数据写到数据库中第四部分:其他参考资料/a/a.asp?B=260&ID=1243284Database Toolbox 2和关系数据库进行数据交换Database 工具箱可以使你使用MATLAB 的数据分析和可视化工具对存储在数据库中的数据进行分析。
在MATLAB 工作环境中,您可以使用结构化查询语言进行:■对数据库中的数据进行读写■使用约束条件对数据库进行操作您可以在MATLAB 中和绝大多数的数据库进行交互,包括Oracle、Sybase、Microsoft SQL Server、MySQL、PostgreSQL 以及Microsoft Access 。
该工具箱还允许您在单个的MATLAB 任务中同时存取多个数据库并且支持事务特性。
它包含了Visual Query Builder (可视化查询工具),它可以使您在不熟悉SQL 的情况下和数据库进行交互。
Visual Query Builder可以快速对您的数据进行存取和图表显示关键特性■支持ODBC/JDBC 连接的数据库接口包括Oracle、Sybase、Microsoft SQLServer、MySQL、PostgreSQL 以及Microsoft Access■从MATLAB 中直接执行查询语句■对于大数据量查询,将增量获取数据■在所有的数据导入和导出的过程中,保留数据类型■单个的MATLAB 任务中可以同时存取多个数据库■从一个数据库中导入数据,完成计算后,将结果输出到另外一个数据库■在单个事务中获取大数据集,或者分割数据,通过多个事务来完成■通过在一个MATLAB 会话中保持数据库连接来减少需要进行输入和输出数据所需要的语句,除非数据库连接被显式关闭■它可以使您在不熟悉SQL 的情况下和数据库进行交互在MATLAB 中对Microsoft Access 数据库进行查询数据库工具箱函数列表数据库访问函数clearwarnings 清除数据库连接警告close 关闭数据库连接commit 数据库改变参数database 连接数据库exec 执行SQL语句和打开油标get 得到数据库属性insert 导出MATLAB单元数组数据到数据库表isconnection 判断数据库连接是否有效isreadonly 判断数据库连接是否只读ping 得到数据库连接信息rollback 撤销数据库变化set 设置数据库连接属性sql2native 转换JDBC SQL 语法为系统本身的SQL语法update 用MATLAB单元数组数据代替数据库表的数据数据库游标访问函数attr 获得的数据集的列属性close 关闭游标cols 获得的数据集的列数值columnnames 获得的数据集的列名称fetch 导入数据到MATLAB单元数组get 得到游标对象属性querytimeout 数据库SQL查询成功的时间rows 获取数据集的行数set 设置游标获取的行限制width 获取数据集的列宽数据库元数据函数bestrowid 得到数据库表唯一行标识columnprivileges 得到数据库列优先权columns 得到数据库表列名称crossreference 得到主健和外健信息dmd 创建数据库元数据对象exportedkeys 得到导出外部健信息get 得到数据库元数据属性importedkeys 得到导入外健信息indexinfo 得到数据库表的索引和统计primarykeys 从数据库表或结构得到主健信息procedurecolumns 得到目录存储程序参数和结果列procedures 得到目录存储程序supports 判断是否支持数据库元数据tableprivileges 得到数据库表优先权tables 得到数据库表名称versioncolumns 得到自动更新表列数据库工具箱让用户使用MATLAB强大数据分析和可视化工具功能处理存储在数据库中的数据的复杂分析。