Matlab中python interp函数1函数使用时有重复的y,但还是想使用怎么办,能解决吗?有高手吗?请教

1. 绘图命令1.1axisaxis 一般用来设置 axes 的样式,包括坐标轴范围,可读比例等 axis([xmin xmax ymin ymax]) axis([xmin xmax ymin ymax zmin zmax cmin cmax]) 坐标轴设置 v = axis axis auto axis manual axis tight axis fill axis ij axis xy axis equal axis image axis square axis vis3d axis normal 坐标轴刻度比例等 axis off axis on 显示与否 axis(axes_handles,...) 根据 axes 设置 [mode,visibility,direction] = axis('state') 返回当前 axes 属性1.2 限定坐标轴显示范围限定特定值 xlim([]); ylim([]); 自动检索最大最小值 axis([min(x) max(x) min(y) max(y)]); % 设置坐标轴在指定的区间 1.3 1.4 空间绘图命令 surf假 设 X=[x1,x2,x3,x4,x5,x6],Y=[y1,y2,y3,y4,y5,y6],Z=(x-x1)*(y-y1)+(x-x2)*(y-y2) +...+(x-x6)*(y-y6) ,Z 为高度。那我怎么画 x,y,z 的三维曲面呢? x=[1:6];%假设 x 为 1:6 y=[4:9];%假设 y 为 4:9 [X, Y] = meshgrid(-5:1:5);%生成平面坐标 Z = (X-x(1)).*(Y-y(1)) + (X-x(2)).*(Y-y(2)) + (X-x(3)).*(Y-y(3)) + (X-x(4)).*(Y-y(4)) + (X-x(5)).*(Y-y(5)) + (X-x(6)).*(Y-y(6)); surf(X,Y,Z)1.5 legend 添加图例1.6 插值函数 interp1MATLAB 中的插值函数为 interp1,其调用格式为: yi= interp1(x,y,xi,'method')其中 x,y 为插值点,yi 为在被插值点 xi 处的插值结果;x,y 为向量, 'method' 表示采用的插值方法, MATLAB 提供的插值方法有几种: 'method'是最邻近插值, 'linear'线性插值; 'spline'三次样条插值; 'cubic'立方插值.缺省时表示线性插 值注意:所有的插值方法都要求 x 是单调的,并且 xi 不能够超过 x 的范围。 例如:在一天 24 小时内,从零点开始每间隔 2 小时测得的环境温度数据分别为 12,9,9,1,0,18 ,24,28,27,25,20,18,15,13, 推测中午 12 点(即 13 点)时的温度. x=0:2:24; y=[12 a=13; y1=interp1(x,y,a,'spline') 结果为: 27.8725 若要得到一天 24 小时的温度曲线,则: xi=0:1/3600:24; yi=interp1(x,y,xi, 'spline'); plot(x,y,'o' ,xi,yi) 1. 1.7 linspace 函数 此函数是常用的用来生成等间距数组的方法。 logspace, colon.也可以用 来生成一些不同条件的数组,但是 linspace 最常用。 2. 2 linspace(a1,a2) 此函数用来生成 a1 到 a2 之间的等间距的数组,我们在 MATLAB 主窗口中 输入如下命令:A=linspace(1,100) 回车:然后会看到如下结果,我们可 以看到生成的结果如下: 结果生成的是 1 到 100 之间的整数, 一共 100 个数字, 我们可以看到默认 情况下 linspace(a1,a2) 是生成包括 a1 a2 在内的等差数组。 9 9 10 18 24 28 27 25 20 18 15 13]; 3. 3 linspace(a1,a2,N) 此函数是用来生成 a1 与 a2 之间等距的数组, 那么我们先举两个例子来讨 论生成的等差数列间距。 我们下面生成 0-9 之间间距为 1 的等差序列,那么我们尝试在 MATLAB 主 窗口中输入如下: B=linspace(0,9,9) 我们可以看到结果如下: B = 0 5.0 6.0 7.0 9.0我们可以看到结果并不是我们想要的, 我们可以发现上面生成的数列间距 是 1.125,而 1.125=(9-0)/(9-1)。下面我们尝试一下另外一个例子。 4. 4 关于如何确定 N 接着上面的例子,我们尝试例子 B=linspace(0,9,10),在 MATLAB 主窗口 中输入 C=linspace(0,9,10),回车,我们可以看到如下结果: C = 0 7 8 1 9 2 3 4 5 6可以看到生成的数组间距为 1,=(9-0)/(10-1), 所以我们确定 N 的方法是依照间距 d=(a2-a1)/(N-1)END1.7 点到直线的距离P-点坐标 1.三维空间 d = norm(cross(Q2-Q1,P-Q1))/norm(Q2-Q1); 2.二维空间 d = abs(det([Q2-Q1,P-Q1]))/norm(Q2-Q1); Q1, Q2 线上两点坐标 % 坐标为列向量 d = abs(det([Q2-Q1;P-Q1]))/norm(Q2-Q1); % 坐标为行向量1.8 求两直线交点坐标S = solve('y=3.01*x-5','y=(-5*x)+20.003','x','y'); S.x S.y1.9 利用 matlab 标记最大值点、最小值点、极值点http://jingyan.baidu.com/article/6d704a131bc8.html1.10 二维杆状图函数 stemHelp 1.11 在 plot 画出的图形中给一个点标上坐标?以及 text 标 注比如有段程序: x=[0:0.2:10]; y=x.^2; plot(x,y); 我想在图中把(3,9)点的坐标标在图上或者用虚线垂直作到坐标轴上标出数据x=[0:0.2:10]; y=x.^2; plot(x,y); hold on text(3,9,' \leftarrow 3^2=9','FontSize',18) stem(3,9)1.12 极坐标绘图 polar(theta,r); 1.13 常用绘图颜色常用颜色 r g 红 绿 b c m y k w蓝 蓝绿 紫红 黄 黑 白具体叙述或更多颜色见‘Matlab 中 plot 函数一共能调用多少种颜色?’ http://www.ilovematlab.cn/thread--1.html (出处: MATLAB 中文论坛)1.14 空间坐标轴名称标注 [X Y] = meshgrid(-8:.5:8); R = sqrt(X.^2 + Y.^2) + Z = sin(R)./R; mesh(Z); title('标题及坐标轴名称展示'); #标题 x1=xlabel('X 轴'); x2=ylabel('Y 轴'); x3=zlabel('Z 轴'); #x 轴标题 #y 轴标题 #z 轴标题set(x1,'Rotation',30); #x 轴名称旋转 set(x2,'Rotation',-30); #y 轴名称旋转 1.15 图像裁剪命令 imcrop 函数http://www.ilovematlab.cn/thread--1.html (出处: MATLAB 中文论坛)1.16plot 函数详解运行下列命令, x=linspace(0,2*pi,100); y=sin(x); h=plot(x,y);get(h) 会显示有关 plot 句柄的所有相关信息。 GET(H) displays all property names and their current values for the graphics object with handle H. 显示如下: DisplayName: '' Annotation: [1x1 hg.Annotation] Color: [0 0 1] LineStyle: '-' LineWidth: 0.5000 Marker: 'none' MarkerSize: 6 MarkerEdgeColor: 'auto' MarkerFaceColor: 'none' XData: [1x100 double] YData: [1x100 double] ZData: [1x0 double] BeingDeleted: 'off' ButtonDownFcn: [] Children: [0x1 double] Clipping: 'on' CreateFcn: [] DeleteFcn: [] BusyAction: 'queue' HandleVisibility: 'on' HitTest: 'on' Interruptible: 'on' Selected: 'off' SelectionHighlight: 'on' Tag: '' Type: 'line' UIContextMenu: [] UserData: [] Visible: 'on' Parent: 170.3105 XDataMode: 'manual' XDataSource: '' YDataSource: '' ZDataSource: ''具体每部分的意义如下: 1. DisplayName: set(h,'DisplayName','Sin Function'); legend show 就是给这个图线起个名字,当运行 legend show 时,就会显示在 legend 上。当绘制很多条图线时,这么做可以避免混乱。不必在最后用 legend 函数一一为每条图线命 名。 2. AnnotationhAnnotation = get(h,'Annotation'); hLegendEntry = get(hAnnotation','LegendInformation'); set(hLegendEntry,'IconDisplayStyle','off'); 设置为 off 的话,该线条将不在 legend 里显示。3.Color: [0 0 1] 4.LineStyle: '-'线的颜色 线型 5.LineWidth: 0.5000 线宽set(h,'Color','r','LineStyle','--','LineWidth',2.0);6, Marker: 'none' 7, MarkerSize: 6标记 标记大小8, MarkerEdgeColor: 'auto' 标记的边框颜色 9, MarkerFaceColor: 'none' 标记的颜色 Marker symbol. Specifies marks displayed at data points. You can set values for the Marker property independently from the LineStyle property. Supported markers are shown in the following table.Marker Specifier '+' 'o' '*' '.' 'x' 'square' or 's'Description Plus sign Circle Asterisk Point Cross Square Marker Specifier Description 'diamond' or 'd' Diamond '^' Upward-pointing triangle 'v' Downward-pointing triangle '&' Right-pointing triangle '&' Left-pointing triangle 'pentagram' or 'p' Five-pointed star (pentagram) 'hexagram' or 'h' Six-pointed star (hexagram) 'none' No marker (default)set(h,'Marker','s',... 'MarkerEdgeColor','k',... 'MarkerFaceColor','g',... 'MarkerSize',10);10,x,y,z 的数据,做动画的时候可重置这些值。 XData: [1x50 double] YData: [1x50 double] ZData: [1x0 double] 例子: x=linspace(pi,2*pi,50); y=sin(x); set(h, 'XData',x,'YData',y);11.BeingDeletedon | {off} Read OnlyThis object is being deleted. The BeingDeleted property provides a mechanism that you can use to determine if objects are in the process of being deleted. MATLAB sets the BeingDeleted property to on when the object's delete function callback is called (see the DeleteFcn property). It remains set to on while the delete function executes, after which the object no longer exists. For example, an object's delete function might call other functions that act on a number of different objects. These functions might not need to perform actions on objects if the objects are going to be deleted, and therefore, can check the object's BeingDeleted property before acting. 12. BusyActioncancel | {queue}Callback routine interruption. The BusyAction property enables you to control how MATLAB handles events that potentially interrupt executing callbacks. If there is a callback function executing, callbacks invoked subsequently always attempt to interrupt it. If the Interruptible property of the object whose callback is executing is set to on (the default), then interruption occurs at the next point where the event queue is processed. If the Interruptible property is off, the BusyAction property (of the object owning the executing callback) determines how MATLAB handles the event. The choices are?cancel ― Discard the event that attempted to execute a second callbackroutine.?queue ― Queue the event that attempted to execute a second callback routineuntil the current callback finishes.13. ButtonDownFcnstring or function handle Button press callback function. A callback that executes whenever you press a mouse button while the pointer is over this object, but not over another graphics object. See theHitTestArea property for information about selecting objects of this type.See the figure's SelectionType property to determine if modifier keys were also pressed. This property can be ? ? ?A string that is a valid MATLAB expression The name of a MATLAB file A function handleSet this property to a function handle that references the callback. The expressions execute in the MATLAB workspace. See Function Handle Callbacks for information on how to use function handles to define the callbacks.14. Childrenarray of graphics object handles Children of the bar object. The handle of a patch object that is the child of this object (whether visible or not). If a child object's HandleVisibility property is callback or off, its handle does not show up in this object's Children property. If you want the handle in theChildren property, set the root ShowHiddenHandles property to on. For example: set(0,'ShowHiddenHandles','on') 15. Clipping {on} | offClipping mode. MATLAB clips graphs to the axes plot box by default. If you setClipping to off, portions of graphs can be displayed outside the axes plot box. Thiscan occur if you create a plot object, set hold to on, freeze axis scaling (axismanual), and then create a larger plot object.16.CreateFcnstring or function handle Callback routine executed during object creation. This property defines a callback that executes when MATLAB creates an object. You must specify the callback during the creation of the object. For example,graphicfcn(y,'CreateFcn',@CallbackFcn)where @CallbackFcn is a function handle that references the callback function andgraphicfcn is the plotting function which creates this object.MATLAB executes this routine after setting all other object properties. Setting this property on an existing object has no effect. The handle of the object whose CreateFcn is being executed is accessible only through the root CallbackObject property, which you can query using gcbo. See Function Handle Callbacks for information on how to use function handles to define the callback function.17. DeleteFcnstring or function handle Callback executed during object deletion. A callback that executes when this object is deleted (e.g., this might happen when you issue a delete command on the object, its parent axes, or the figure containing it). MATLAB executes the callback before destroying the object's properties so the callback routine can query these values. The handle of the object whose DeleteFcn is being executed is accessible only through the root CallbackObject property, which can be queried using gcbo. 18.HandleVisibility{on} | callback | off Control access to object's handle by command-line users and GUIs. This property determines when an object's handle is visible in its parent's list of children.HandleVisibility is useful for preventing command-line users from accidentallyaccessing objects that you need to protect for some reason.? ?on ― Handles are always visible when HandleVisibility is on. callback ― Setting HandleVisibility to callback causes handles tobe visible from within callback routines or functions invoked by callback routines, but not from within functions invoked from the command line. This provides a means to protect GUIs from command-line users, while allowing callback routines to have access to object handles.?off ― Setting HandleVisibility to off makes handles invisible at alltimes. This might be necessary when a callback invokes a function that might potentially damage the GUI (such as evaluating a user-typed string) and so temporarily hides its own handles during the execution of that function.Functions Affected by Handle Visibility When a handle is not visible in its parent's list of children, it cannot be returned by functions that obtain handles by searching the object hierarchy or querying handle properties. This includes get, findobj, gca, gcf, gco, newplot, cla, clf, andclose.Properties Affected by Handle Visibility When a handle's visibility is restricted using callback or off, the object's handle does not appear in its parent's Children property, figures do not appear in the root'sCurrentFigure property, objects do not appear in the root's CallbackObjectproperty or in the figure's CurrentObject property, and axes do not appear in their parent's CurrentAxes property. Overriding Handle Visibility You can set the root ShowHiddenHandles property to on to make all handles visible regardless of their HandleVisibility settings (this does not affect the values of theHandleVisibility properties). See also findall.Handle Validity Handles that are hidden are still valid. If you know an object's handle, you can set andget its properties and pass it to any function that operates on handles.19.HitTest{on} | offSelectable by mouse click. HitTest determines whether this object can become the current object (as returned by the gco command and the figure CurrentObject property) as a result of a mouse click on the objects that compose the area graph. IfHitTest is off, clicking this object selects the object below it (which is usually theaxes containing it).20. Interruptible {on} | offCallback routine interruption mode. The Interruptible property controls whether an object's callback can be interrupted by callbacks invoked subsequently. Only callbacks defined for the ButtonDownFcn property are affected by theInterruptible property. MATLAB checks for events that can interrupt a callbackonly when it encounters a drawnow, figure, getframe, or pause command in the routine. See the BusyAction property for related information. Setting Interruptible to on allows any graphics object's callback to interrupt callback routines originating from a bar property. Note that MATLAB does not save the state of variables or the display (e.g., the handle returned by the gca or gcf command) when an interruption occurs. 21.Selectedon | {off}Is object selected? When you set this property to on, MATLAB displays selection &handles& at the corners and midpoints if the SelectionHighlight property is alsoon (the default). You can, for example, define the ButtonDownFcn callback to set thisproperty to on, thereby indicating that this particular object is selected. This property is also set to on when an object is manually selected in plot edit mode.22. SelectionHighlight {on} | offObjects are highlighted when selected. When the Selected property is on, MATLAB indicates the selected state by drawing four edge handles and four corner handles. WhenSelectionHighlight is off, MATLAB does not draw the handles except when inplot edit mode and objects are selected manually.23. Tagstring User-specified object label. The Tag property provides a means to identify graphics objects with a user-specified label. This is particularly useful when you are constructing interactive graphics programs that would otherwise need to define object handles as global variables or pass them as arguments between callbacks. You can define Tag as any string. For example, you might create an areaseries object and set the Tag property. t = area(Y,'Tag','area1')When you want to access objects of a given type, you can use findobj to find the object's handle. The following statement changes the FaceColor property of the object whose Tag is area1.set(findobj('Tag','area1'),'FaceColor','red') 24. Typestring (read only) Type of graphics object. This property contains a string that identifies the class of the graphics object. For areaseries objects, Type is 'hggroup'. The following statement finds all the hggroup objects in the current axes.t = findobj(gca,'Type','hggroup'); 25. UIContextMenuhandle of a uicontextmenu object Associate a context menu with this object. Assign this property the handle of a uicontextmenu object created in the object's parent figure. Use the uicontextmenu function to create the context menu. MATLAB displays the context menu whenever you right-click over the object.26. UserDataarray User-specified data. This property can be any data you want to associate with this object (including cell arrays and structures). The object does not set values for this property, but you can access it using the set and get functions. 27. Visible {on} | offVisibility of this object and its children. By default, a new object's visibility is on. This means all children of the object are visible unless the child object's Visible property is set to off. Setting an object's Visible property to off prevents the object from being displayed. However, the object still exists and you can set and query its properties.28. XDataMode{auto} | manual Use automatic or user-specified x-axis values. If you specify XData (by setting theXData property or specifying the x input argument), MATLAB sets this property to manual and uses the specified values to label the x-axis.If you set XDataMode to auto after having specified XData, MATLAB resets the x-axis ticks to 1:size(YData,1) or to the column indices of the ZData, overwriting any previous values for XData.29. XDataSourcestring (MATLAB variable) Link XData to MATLAB variable. Set this property to a MATLAB variable that is evaluated in the base workspace to generate the XData. MATLAB reevaluates this property only when you set it. Therefore, a change to workspace variables appearing in an expression does not change XData. You can use the refreshdata function to force an update of the object's data.refreshdata also enables you to specify that the data source variable be evaluated inthe workspace of a function from which you call refreshdata.30. YDataSourcestring (MATLAB variable) Link YData to MATLAB variable. Set this property to a MATLAB variable that is evaluated in the base workspace to generate the YData. MATLAB reevaluates this property only when you set it. Therefore, a change to workspace variables appearing in an expression does not change YData. You can use the refreshdata function to force an update of the object's data.refreshdata also enables you to specify that the data source variable be evaluated inthe workspace of a function from which you call refreshdata. 英文部分链接: http://www.mathworks.com/access/helpdesk/help/techdoc/ref/areaseriesproperties.html http://www.mathworks.com/access/helpdesk/help/techdoc/ref/plot.html1.17plot 画双纵坐标实例x = 0:0.01:20; y1 = 200*exp(-0.05*x).*sin(x); y2 = 0.8*exp(-0.5*x).*sin(10*x); [AX,H1,H2] = plotyy(x,y1,x,y2,'plot'); set(AX(1),'XColor','k','YColor','b'); set(AX(2),'XColor','k','YColor','r'); HH1=get(AX(1),'Ylabel'); set(HH1,'String','Left Y-axis'); set(HH1,'color','b'); HH2=get(AX(2),'Ylabel'); set(HH2,'String','Right Y-axis'); set(HH2,'color','r'); set(H1,'LineStyle','-'); set(H1,'color','b'); set(H2,'LineStyle',':'); set(H2,'color','r'); legend([H1,H2],{'y1 = 200*exp(-0.05*x).*sin(x)';'y2 = 0.8*exp(-0.5*x).*sin(10*x)'}); xlabel('Zero to 20 musec.'); title('Labeling plotyy');Q:右边用蓝色圈起来的 tick 能去掉吗?由于用 plotyy 画图,为了使图尽量地 显示出来, 用了 set(AX(1),'YLimMode','auto'),但这样可能会导致左边 AX(1) 和右边 AX(2)的 tick 的间距不一样,影响美观。或者说能不能使 plotyy 画出的 图两边的 tick 间距是一样的,这样在图形右边的 tick 就会重合在一起. A:如果只是想让 plotyy 的图美一些,可以使用其如下形式的调用方式: [AX,H1,H2] = plotyy(...) 其中 AX(2)就是右边 Axes 对象的句柄,拿到它以后就可以 set 或者 get 来处理 了,也可以把其 ytick 关掉。 A:也可以用 line 语句来画,就没有左边和上边的线了。 Q:plotyy(X1,Y1,X2,Y2,FUN1,FUN2),FUN1 和 FUN2 应该怎么写? A:这两个 FUN 代表 plotyy 不一定要用两个 plot,比如下面的例子,一条曲线 用 plot,一条用 semilogy x1=1:0.1:100; x2=x1; y1=x1; y2=x2.^3; plotyy(x1,y1,x2,y2,@plot,@semilogy)MATLAB 画双纵坐标具有两个纵坐标标度的图形 在 MATLAB 中,如果需要绘制出具有不同纵坐标标度的两个图形,可以使用 plotyy 绘图函 数。调用格式为: plotyy(x1,y1,x2,y2) 其中 x1,y1 对应一条曲线,x2,y2 对应另一条曲线。横坐标的标度相同,纵坐标有两个,左 纵坐标用于 x1,y1 数据对,右纵坐标用于 x2,y2 数据对。 双 y 轴坐标可以用 plotyy(x,y1,x,y2)来实现 双 x 坐标可以用 set(gca,'xaxislocation','bottom','xticklabel',{'0','1','2','3','4'}) (假设 x 轴的标注为 1,2,3,4) set(gca,'xaxislocation','top','xticklabel',{'0','1','2','3','4'}) 进行相应的设置【 * 例 10.7.3 -1 】制作一个双坐标系用来表现高压和低温两个不同量的过渡过程。 tp=(0:100)/100*5;yp=8+4*(1-exp(-0.8*tp).*cos(3*tp)); % 压力数据 tt=(0:500)/500*40;yt=120+40*(1-exp(-0.05*tt).*cos(tt)); % 温度数据 % 产生双坐标系图形 clf reset,h_ap=axes('Position',[0.13,0.13,0.7,0.75]); %&4& set(h_ap,'Xcolor','b','Ycolor','b','Xlim',[0,5],'Ylim',[0,15]); nx=10;ny=6; %&6& pxtick=0:((5-0)/nx):5;pytick=0:((15-0)/ny):15; %&7& set(h_ap,'Xtick',pxtick,'Ytick',pytick,'Xgrid','on','Ygrid','on') h_linet=line(tp,yp,'Color','b'); %&9& set(get(h_ap,'Xlabel'),'String',' 时间 /rightarrow (分) ') set(get(h_ap,'Ylabel'),'String',' 压力 /rightarrow(/times10 ^{5} Pa )') h_at=axes('Position',get(h_ap,'Position')); %&12& set(h_at,'Color','none','Xcolor','r','Ycolor','r'); %&13& set(h_at,'Xaxislocation','top') %&14& set(h_at,'Yaxislocation','right','Ydir','rev') %&15& set(get(h_at,'Xlabel'),'String','/fontsize{15}/fontname{ 隶书 } 时间 /rightarrow (分) ') set(get(h_at,'Ylabel'),'String',' ( {/circ}C )/fontsize{15} /leftarrow /fontname{ 隶书 } 零下温度 ') set(h_at,'Ylim',[0,210]) %&18& line(tt,yt,'Color','r','Parent',h_at) %&19& xpm=get(h_at,'Xlim'); %&20& txtick=xpm(1):((xpm(2)-xpm(1))/nx):xpm(2); %&21& tytick=0:((210-0)/ny):210; %&22& set(h_at,'Xtick',txtick,'Ytick',tytick) %&23&来源:http://hi.baidu.com/goodenoughcui/blog/item/e9a00b8b7ad52d6f9e2fb4d2.html ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~ 实例(已验证): x=0:0.1:2* y1=sin(x); y2=cos(x); [AX]=plotyy(x,y1,x,y2); set(get(gca,'xlabel'),'string','X-axis'); set(get(AX(1),'Ylabel'),'string','left Y-axis'); set(get(AX(2),'Ylabel'),'string','right Y-axis'); set(gca,'xTick',[0:0.5:7]); set(AX(1),'yTick',[-1:0.2:1]); set(AX(2),'yTick',[-1:0.5:1]);尚存在问题:这种设置方法,对各个轴的最小刻度单位可以设置,但是刻度范围(x 取(0~ 7),y1 取(-1~1))不能设置。
修改~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~ clc clear all close all runoff=[
]; sed=[0.105 0.094 0.156 1.264 m=1:10; [ax,h1,h2]=plotyy(m,runoff,m,sed); %h-- line handle set(get(ax(1),'Ylabel'),'string','Runoff (m^3/s))','color','r') %y1 set(get(ax(2),'Ylabel'),'string','Sediment concentration (kg/m^3)','color','k') %y2 xlabel('Month') set(h1,'linestyle','-','color','r'); set(h2,'linestyle','- -','color','k'); legend([h1 h2],'runoff','sediment concentration') %标注两条线 legend('boxoff') % box off set(ax(:),'Ycolor','k') %设定两个 Y 轴的颜色为黑色 set(ax(1),'ytick',[0:]); %设置 y 轴间隔 set(ax(2),'ytick',[0:0.1:1.5]) set(ax,'xlim',[1 12]) % 设置 x 轴范围 hold on scatter(ax(1),4,22900,'r*') axes(ax(2)); hold on scatter(4,1.264,'ro') 0.363 0.429 0.731 0.682 0.654 0.290]; 22.1true 和 falsehttp://jingyan.baidu.com/article/b87fe19e993bd.html 2.2size 用法我们以向量 V=[1 2 3 4];矩阵 A=[1 2 3 4 ;5 6 7 8;9 10 11 12]为例,介 绍一下我总结的 size 函数的用法。size 函数顾名思义,就是求取长度的函数。 下面我们就具体的用法进行阐释。数据如下:1. 求矩阵的行数 我们都知道向量其实是特殊的矩阵,行数为 1 而已。 这里我们求取 V 和 A 的行数,在 MATLAB 主窗口中输入,a1=size(V,1),a2=size(A,1), 回车从结果可以看出,向量 V 的行数为 1,矩阵 V 的行数为 3,在 size(V,1)语句中,1 就代表求矩阵的行数。 2. 求矩阵的列数 下面我们分别求取向量 V 和矩阵 A 的列数,在 MATLAB 主窗口中输入,a1 = s i z e ( V , 2 ) , a 2 = s i z e ( A , 2 ) , 回 车我们可以 看到向量 V 的列数为 4,矩阵 A 的列数为 4,在 size(V,2)语句中,2 就代 表求矩阵的列数。 3. 求矩阵的行列数 有时候我们需要直接得到矩阵的维数,并分别赋予变量,在 MATLAB 主窗 口中输入, a 1 = s i z e ( V ) , a 2 = s i z e ( A ) , 回 车则返回的结果为两个向量, 其中向量 a1 存储的是 V 的行列数,第一个元素是 V 的行数,第二个元素 为 V 的列数。a2 亦是如此。2.3 对多个变量同时赋值[Y1, Y2, Y3, ...] = deal(X),即 Y1=Y2=Y3=X [Y1, Y2, Y3, ...] = deal(X1, X2, X3, ?),即 Y1=X1,Y2=X2,Y3=X3 详情见: http://wenku.baidu.com/link?url=0SemmLj0xJn9zb4Z3kSBAw4pnYafn_tHV5HQvs-wq swABgNwJr0e1KMCfEKGjfKs3-kpq5r7Tqygm01uVG8YurZSQPmt9BAeqHkbrsAgdIa2.4 统计术语SSE(和方差、误差平方和):The sum of squares due to error MSE(均方差、方差):Mean squared error RMSE(均方根、标准差):Root mean squared error R-square(确定系数):Coefficient of determination Adjusted R-square:Degree-of-freedom adjusted coefficient of determination 2.5 生成系列变量x=sym('x',[1,2]) w=(1:2).*x y=sum(w)2.6 多项式赋值问题针对 2.5 中生成的 y,如何给 x1 和 x2 赋值,获得 y 值?2.7 一般 MATLAB 问题http://www.ilovematlab.cn/forum.php?mod=viewthread&tid=443246&extra=&auth orid=854642&page=12.8 逻辑语句 ||:or2.9 三项连加函数a=rand(3,1) [b1,i1]=min(a); [b3,i2]=max(a); b2=a( sum( 1:size(a) )-i1-i2 );2.10randn,randi,rand 的用法以及区别1,rand 生成均匀分布的伪随机数。分布在(0~1)之间 主要语法:rand(m,n)生成 m 行 n 列的均匀分布的伪随机数 rand(m,n,'double')生成指定精度的均匀分布的伪随机数,参数还可以 是'single' rand(RandStream,m,n)利用指定的 RandStream(我理解为随机种子)生 成伪 随机数2,randn 生成标准正态分布的伪随机数(均值为 0,方差为 1) 主要语法:和上面一样3, randi 生成均匀分布的伪随机整数 主要语法:randi(iMax)在开区间(0,iMax)生成均匀分布的伪随机整数 randi(iMax,m,n)在开区间(0,iMax)生成 mXn 型随机矩阵 r = randi([iMin,iMax],m,n)在开区间(iMin,iMax)生成 mXn 型随机 矩阵2.11textreadhttp://blog.sina.com.cn/s/blog_9ebju.html help2.12linspace(a1,a2,N),间距 d=(a2-a1)/(N-1)x=linspace(0,2*pi,100);2.13 2.15MATLAB 工作路径问题http://jingyan.baidu.com/article/495ba841f60b2238b20ede7c.html 3.实例3.1 求圆度(1)用概率求解问题 http://www.ilovematlab.cn/forum.php?mod=viewthread&s_tid=followedthread&tid =141384.传递函数4.1.pzamp 返回传递函数的零点和极点Sys = s+2 -------------s^2 + 5 s + 10 pzmap(Sys)命令显示如下,零点为圆圈,极点为×。 5.guide5.1 在 guide 坐标系中载入图片在按钮【选择需要识别的图片】右击 View Callbacks→Callback,进入回调函数目 录。 编写回调函数如下:axes(handles.axes1) RGB=imread('p.jpg'); imshow(RGB);%将 Tag 值为 axes1 的坐标轴置为当前 %读取名为 p.jpg 的图片 %显示图片 6.矩阵6.1 MATLAB 中矩阵各列求和,各行求和,所有元素求和http://jingyan.baidu.com/article/3c48dd349ac816e10be358e3.html 2.15 求最大公倍数和最大公约数 求最小公倍数 lcm 求最大公约数 gcd6.2norm 求矩阵范数1. 对于矩阵 我们以下面矩阵为例: A= 0 3 6 1 4 7 2 5 8在 MATLAB 中分别输入如下命令: norm(A)/norm(A,2),返回的是矩阵 A 的二范数, (二范数 j 就是矩阵 A 的 2 范数 就是 A 的转置矩阵乘以 A 特征根最大值的开根号) norm(A,1),返回矩阵的 1 泛数,就是最大一列的和,从上面矩阵看,norm(A,1)=15 2. 2 norm(A,'inf') 返回矩阵的无穷泛数,也就是最大一行的和,norm(A,'inf')=21 norm(A,'fro') 返回矩阵的 Frobenius 范数,3. 3 对于向量: 我们以向量 B= 0 1 2为例进行介绍。 在 MATLAB 中分别输入如下命令: 当 P 为正整数时,norm(B,p)=sum(abs(A).^p)^(1/p) norm(B,2)=norm(B)=5^0.5=2.2361 norm(B,1)=3 norm(B,'inf')=max(abs(B))=2 norm(B,'fro')B 的 Frobenius 范数;4. 4 norm(B,'inf')=max(abs(B))=2 norm(B,'fro')B 的 Frobenius 范数;6.3 寻找矩阵极值对应的下标A=[0,1,1,0,1,0,1,1]; B=[23,23,25,24,25,26,21,22]; && [Y]=max(B(A==1)) Y= 25另:find(B==max(B(A==1)))可以返回当 A=1 时,B 中对应项中最大值的下标。6.4det(A)求特征值A=[16 3 2 13;5 10 11 8;9 6 7 12;4 15 14 1]; d=det(A) 6.5 如何给已有矩阵插入一行或一列值a=[1 2 3 4]; b=[4 5 6 7] c=[a;b] c= 1 4 a=[1 2 3 4]'; b=[4 5 6 7]'; c=[a,b] c= 1 2 3 4 4 5 6 7 2 5 3 6 4 76.6 截取矩阵某一部分的函数假设一个矩阵 A,大小为 M*N,我想截取 A 的一部分,这一部分是一个矩形, 该矩形的左上角点坐标为(Xmin,Ymin),右下角坐标为(Xmax,Ymax)。 a = rand(10,10) left = 2; right = 4; top = 1; bottom = 6; b = a(top:bottom,left:right) http://www.ilovematlab.cn/thread-.html (出处: MATLAB 中文论坛)7 函数拟合7.1 线性拟合 polyfitp=polyfit(x,y,n)7.2polyvaly = polyval(p,x) 返回 n 次多项式在 x 处的值。输入变量 p 是一个长度为 n+1 的向量,其元素 为按降幂排列的多项式系数。 y=p1*x^n+p2*x^(n-1)+...+pn*x+p(n+1) x 可以是一个矩阵或者一个向量,在这两种情况下, polyval 计算在 X 中任意元 素处的多项式 p 的估值。 举例 对多项式 p(x)=3*x^2+2*x+1,计算在 x=5,7,9 的值。 && p = [3 2 1]; && x=[5,7,9]; && polyval(p,[5 7 9]) %结果为 ans = 86 162 262 7.3 指定函数拟合《MATLAB 在数学建模中的应用》P5――P6 %Fit(x,y,f)中,x 和 y 必须是 n*1 的矩阵。8 解方程8.1 可以解析求解的微分方程。dsolve()调用格式为: y=dsolve(f1,f2,...,fmO; y=dsolve(f1,f2,...,fm,'x'); 如下面的例子,求解了微分方程 u=exp(-5*t)*cos(2*t-1)+5; uu=5*diff(u,t,2)+4*diff(u,t)+2*u; y=dsolve(['D4y+10*D3y+35*D2y+50*Dy+24*y=87*exp(-5*t)*cos(2*t-1)+92*ex p(-5*t)*sin(2*t-1)+10']) yc=latex(y) 将 yc 的内容 copy 到 latex 中编译,得到结果。8.2matlab 求解微分方程――个人总结http://www.ilovematlab.cn/thread-646-1-1.html (出处: MATLAB 中文论坛) 8.3 用 dsolve 解微分方程基本的使用方式是 dsolve('equ'); 其中,equ 表示方程,返回结果为带有常量的符号解, 例一: syms y(x); dsolve(diff(y) == y+ 1) 或者 dsolve('Dy = y + 1','x') 都是 dy/dx = y + 1 的解 高阶情况: Dy = diff(y); D2y = diff(y, 2); 2 例二: 使用 D 代替 diff 时,默认变量为 t, 如 dsolve('D2y = x*y') ans = C27*exp(t*x^(1/2)) + C28*exp(-t*x^(1/2)) 要使变量为 x 使用 && dsolve('D2y = x*y','x') ans = C30*airy(0, x) + C31*airy(2, x)最近有人问有关微分方程求解问题特举一例供大家参考: dsolve 调用格式:dsolve('equ1','equ2',..........'equN') 另外要注意: 在微分方程表达式输入中, 以大写字母 D 来表示微分, D,D2,.......Dn 分别表示一阶,二阶和 n 阶 2dx/dt+dy/dt-y=exp(-t) dx/dt+x+y=0 首先求解微分方程的通解: s=dsolve('2*Dx+Dy-y=exp(-t)','Dx+x+y=0');%求解微分方程组的通解 && s.x %微分方程组变量 x 的通解 ans = -C1*exp((1+2^(1/2))*t)-C2*exp(-(2^(1/2)-1)*t)+1/2*C1*exp((1+2^(1/2))*t)*2^(1/2)-1 /2*C2*exp(-(2^(1/2)-1)*t)*2^(1/2)-1/2*exp(-t) && s.y %微分方程组变量 y 的通解 ans = C1*exp((1+2^(1/2))*t)+C2*exp(-(2^(1/2)-1)*t) 然后根据初始条件,求解微分方程组的特解: 其中初始条件:x(0)=1.5,y(0)=0 && s=dsolve('2*Dx+Dy-y=exp(-t)','dx+x+y=0','x(0)=1.5','y(0)=0');%微分方程组在给定 初始条件下的特解 Warning: Explicit solution could not be found. & In dsolve at 333 && s=dsolve('2*Dx+Dy-y=exp(-t)','Dx+x+y=0','x(0)=1.5','y(0)=0');%微分方程组在给定 初始条件下的特解 && s.xans = -2^(1/2)*exp((1+2^(1/2))*t)+2^(1/2)*exp(-(2^(1/2)-1)*t)+exp((1+2^(1/2))*t)+exp(-(2 ^(1/2)-1)*t)-1/2*exp(-t) && s.y ans =2^(1/2)*exp((1+2^(1/2))*t)-2^(1/2)*exp(-(2^(1/2)-1)*t) && %或者使用下面命令直接获取 x,y 的特解 && [x,y]=dsolve('2*Dx+Dy-y=exp(-t)','Dx+x+y=0','x(0)=1.5','y(0)=0') x =-2^(1/2)*exp((1+2^(1/2))*t)+2^(1/2)*exp(-(2^(1/2)-1)*t)+exp((1+2^(1/2))*t)+exp(-( 2^(1/2)-1)*t)-1/2*exp(-t) y =2^(1/2)*exp((1+2^(1/2))*t)-2^(1/2)*exp(-(2^(1/2)-1)*t)8.5 使用 solve 函数解方程,有已经赋值的字母变量,解不 了呢?举一个简单的例子,例如: a =2 s = solve('x+a=0') 这样算出来是 x = -a ,而我想要 x = -2, (1) a=2; eq=x+a; s=solve(eq,x)9 规划问题9.1linprog 的用法见《MATLAB 在数学建模中的应用》P18――P21求 min f'x 约束条件: Ax&=b 等式约束条件: Aeqx=beq lb&=x&=ub linprog 函数的调用格式如下: linprog 中 f 都是求最小值,这个要记住。 A 和 b 是不等式约束条件的参数。 Aeq 和 beq 是等式约束条件的参数。 lb 和 ub 为 x 取值的取值范围。 函数使用形式:1. x=linprog(f,A,b) 2. x=linprog(f,A,b,Aeq,beq) 3. x=linprog(f,A,b,Aeq,beq,lb,ub) 4. x=linprog(f,A,b,Aeq,beq,lb,ub,x0) 5. x=linprog(f,A,b,Aeq,beq,lb,ub,x0,options) 6. [x,fval]=linprog(…) 7. [x, fval, exitflag]=linprog(…) 8. [x, fval, exitflag, output]=linprog(…) 9. [x, fval, exitflag, output, lambda]=linprog(…) 一般主要用的是:1. x=linprog(f,A,b,Aep,beq,lb,ub); 设定中主要要注意的就是参数的维数是否于使用的相对应。如:a+b+c&30 c&15 b&10 函数:f = 10*a+20*b+30*c 因为 linprog 求的是最小值,一次我们改为:f = -(10*a+20*b+30*c) 这样我们有了函数,然后:根据约束条件不等式,有:1. A = [1 1 1;0 0 1;0 1 0] 2. b = [30 15 10] 但这样算出来的结果大家会发现是小数,也可能是负数。因此我们加入 a b c 取值的上下限 1. lb = [0 0 0] 2. ub = [30 30 30] 如果在计算中需要得到小数的结果,只要写成 0.00 或者 30.00 就可以了 最后带入函数计算就可以了 注意:1) f,A,b,Aep,beq,lb,ub 的维数应相同。 2) A,b,Aep,beq,可写成矩阵形式,表达多个式子。9.2 非线性规划 fmincon《MATLAB 在数学建模中的应用》P22――P249.3 二次规划 quadprog《MATLAB 在数学建模中的应用》P24――P269.4 任意规划问题――罚函数法《MATLAB 在数学建模中的应用》P25――P269.5 整数规划问题和随机取样计算法《MATLAB 在数学建模中的应用》P26――P2810 典型问题10.1 对函数中变量的赋值问题在这三行语句中,生成 y。如何在之后对 x1 和 x2 进行赋值,进而获得 y 的值。 如是 x1=3,x2=5,求 y。 x=sym('x',[1,2]) w=(1:2).*x y=sum(w) 另外,为何在 workplace 中没有 x1,x2,此时这两者还是变量吗?回答 x=sym('x',[1,2]); w=(1:2).*x; y=sum(w) x1=3; x2=5; subs(y) 在 x1,x2 赋值之前,x1,x2 是 sym 类型的数据,不是变量。10.2 取整函数 floor、round、ceil、fix 区别Matlab 取整函数有: fix, floor, ceil, round.具体应用方法如下: fix 朝零方向取整,如 fix(-1.3)=-1; fix(1.3)=1; floor,顾名思义,就是地板,所以是取比它小的整数,即朝负无穷方向取整,如 floor(-1.3)=-2; floor(1.3)=1;floor(-1.8)=-2,floor(1.8)=1 ceil,与 floor 相反,它的意思是天花板,也就是取比它大的最小整数,即朝正无 穷方向取整,如 ceil(-1.3)=-1; ceil(1.3)=2;ceil(-1.8)=-1,ceil(1.8)=2 round 四 舍 五 入 到 最 近 的 整 round(-1.3)=-1;round(-1.52)=-2;round(1.3)=1;round(1.52)=2。 数 , 如注意: 要是输入 floor(2.55) ans=2要是输入 floor 2.55 ans= 50 46 53 53原因:那是因为 matlab 会先把 2.55 四个字符转换成 ascii 玛,然后计算每个 ascii 码的 floor。所以数值型的计算函数通常都必须带括号。10.3 计时函数 tic 和 toc 记录 matlab 命令执行的时间。tic 用来保存当前时间,而后使用 toc 来记录程序完成时间。 两者往往结合使用,用法如下: tic operations toc 显示时间单位:秒11.整体理解11.1Matlab 中 有 15 种 基 本 数 据 类 型 15:18:41)Matlab 中有 15 种基本数据类型,主要是整型、浮点、逻辑、字符、日期和时 间、结构数组、单元格数组以及函数句柄等。 1、 整型: (int8; uint8; int16; uint16; int32; uint32; int64; uint64) 通过 intmax(class) 和 intmin(class) 函数返回该类整型的最大值和最小值, 例如 intmax( ‘int8’ )=127; 2、浮点: (single;double)( 浮点数:REALMAX('double')和 REALMAX('single')分别返回双精度浮点和单精度浮 点的最大值,REALMIN('double')和 REALMIN ('single')分别返回双精度浮点和单精 度浮点的最小值。 3、逻辑:(logical) Logical:下例是逻辑索引在矩阵操作中的应用,将 5*5 矩阵中大于 0.5 的元素 设定为 0: A = rand(5); A(A&0.5)=0; 4、字符:(char) Matlab 中的输入字符需使用单引号。字符串存储为字符数组,每个元素占用 一个 ASCII 字符。如日期字符:DateString=’9/16/2001’实际上是一个 1 行 9 列 向量。构成矩阵或向量的行字符串长度必须相同。可以使用 char 函数构建字符 数组,使用 strcat 函数连接字符。 例如, 命令 name = ['abc' ; 'abcd'] 将触发错误警告, 因为两个字符串的长度不等, 此时可以通过空字符凑齐如:name = ['abc ' ; 'abcd'],更简单的办法是使用 char 函数:char(‘abc’,’abcd’),Matlab 自动填充空字符以使长度相等,因此字 符串矩阵的列纬总是等于最长字符串的字符数. 例如 size(char(‘abc’,’abcd’))返回结果[2,4],即字符串’abc’实际存在的是’ abc ’ ,此时如需提取矩阵中的某一字符元素,需要使用 deblank 函数移除空格 如 name =char(‘abc’,’abcd’); deblank(name(1,:))。 此外,Matlab 同时提供一种更灵活的单元格数组方法,使用函数 cellstr 可以 将字符串数组转换为单元格数组: data= char(‘abc’,’abcd’) length(data(1,:)) -&? 4 cdata=cellstr(data) length(cdata{1}) -&?3 常用的字符操作函数 blanks(n) 返回 n 个空字符 deblank(s) 移除字符串尾部包含的空字符 (string) 将字符串作为命令执行 findstr(s1,s2) 搜索字符串 ischar(s) 判断是否字符串 isletter(s) 判断是否字母 lower(s) 转换小写 upper(s) 转换大写 strcmp(s1,s2) 比较字符串是否相同 strncmp(s1,s2,n) 比较字符串中的前 n 个字符是否相同 strrep(s1,s2,s3) 将 s1 中的字符 s2 替换为 s3 5、日期和时间 Matlab 提供三种日期格式: 日期字符串如’ ’ , 日期序列数如 729300 (0000 年 1 月 1 日为 1) 以及日期向量如
0 0 0, 依次为年月日时分秒。 常用的日期操作函数 datestr(d,f) 将日期数字转换为字符串 datenum(str,f) 将字符串转换为日期数字 datevec(str) 日期字符串转换向量 weekday(d) 计算星期数 eomday(yr,mth) 计算指定月份最后一天 calendar(str) 返回日历矩阵 clock 当前日期和时间的日期向量 date 当前日期字符串 now 当前日期和时间的序列数 6、结构 结构是包含已命名“数据容器”或字段的数组。结构中的字段可以包含任何 数据。 7、构建结构数组 (1)赋值方法 下面的赋值命令产生一个名为 patient 的结构数组,该数组包含三个字段: patient.name = 'John Doe'; patient.billing = 127.00; patient.test = [79 75 73; 180 178 177.5; 220 210 205]; 在命令区内输入 patient 可以查看结构信息: name: 'John Doe' billing: 127 test: [3x3 double] 继续赋值可扩展该结构数组: patient(2).name = 'Ann Lane'; patient(2).billing = 28.50; patient(2).test = [68 70 68; 118 118 119; 172 170 169]; 赋值后结构数组变为[1 2]。 (2)构建结构数组:struct 函数 函数基本形式为:strArray = struct('field1',val1,'field2',val2, ...) 例如: weather(1) = struct('temp', 72,'rainfall', 0.0); weather(2) = struct('temp', 71,'rainfall', 0.1); weather = repmat(struct('temp', 72, 'rainfall', 0.0), 1, 3); weather = struct('temp', {68, 80, 72}, 'rainfall', {0.2, 0.4, 0.0}); (3)访问结构数据 以下都是合法的结构数组访问命令: mypatients = patient(1:2) 获取子结构数据 mypatients(1) 访问结构数据 patient(2).name 访问结构数据中的特定字段 patient(3).test(2,2) 访问结构数据中的特定字段(该字段为数组) bills = [patient.billing] 访问多个结构 tests = {patient(1:2).test} 提取结构数据转换成单元格数组 使用结构字段的动态名称 通过 structName.(expression_r_r_r)可以赋予结构字段名称并访问数据。 例如字 段名为 expression_r_r_r、结构名为 structName,访问其中第 7 行 1 至 25 列数据 可以使用命令:structName.(expression_r_r_r)(7,1:25)。 例如,存在一个学生每周成绩数据结构数组,其数据通过以下方式建立: testscores.wang.week(1:25) = ... [95 89 76 82 79 92 94 92 89 81 75 93 ... 85 84 83 86 85 90 82 82 84 79 96 88 98]; testscores.chen.week(1:25) = ... [87 80 91 84 99 87 93 87 97 87 82 89 ... 86 82 90 98 75 79 92 84 90 93 84 78 81]; 即结构名为 testscores,字段使用每个学生的名称命名,分别为 wang 和 chen, 每个学生下面包含名为 week 的成绩结构数组。 现计算给定结构名称、学生名称和起止周数的平均分数。 在命令窗口中输入 edit avgscore.m,输入以下代码后保存文件: function avg = avgscore(struct,student, first, last) avg = sum(struct.(student).week(first:last))/(last - first + 1); 在命名窗口中输入:avgscore(testscores, 'chen', 7, 22) 计算学生陈从第 7 周到 第 22 周的平均分数。 (4)添加和删除结构字段 命令[struct](index).(field)可添加或修改字段。如 patient(2).ssn = '000-00-0000' 在 结构 patient 中添加一个名为 ssn 的字段。 删除字段使用 rmfield 函数, 如 patient2 = rmfield(patient, 'name') 删除 name 字段 并产生新的结构。 8、单元格数组:(cell) 单元格数组提供了不同类型数据的存储机制,可以储存任意类型和任意纬度 的数组。 访问单元格数组的规则和其他数组相同,区别在于需要使用花括号{}访问,例如 A{2,5}访问单元格数组 A 中的第 2 行第 5 列单元格。 (1)构建单元格数组:赋值方法 使用花括号标识可直接创建单元格数组,如: A(1,1) = {[1 4 3; 0 5 8; 7 2 9]}; A(1,2) = {'abcd'}; A(2,1) = {3+7i}; A(2,2) = {-pi:pi/10:pi}; 上述命令创建 2*2 的单元格数组 A 。继续添加单元格元素直接使用赋值如 A(2,3)={5}即可,注意需使用花括号标识。简化的方法是结合使用花括号(单元格 数组)和方括号()创建,如 C = {[1 2], [3 4]; [5 6], [7 8]}; (2)构建单元格数组:函数方法 Cell 函数。如: B = cell(2, 3); B(1,3) = {1:3}; (3)访问数据 通过索引可直接访问单元格数组中的数据元素,例如: N{1,1} = [1 2; 4 5]; N{1,2} = 'Name'; N{2,1} = 2-4i; N{2,2} = 7; c = N{1,2} d = N{1,1}(2,2) 9、函数句柄 函数句柄是用于间接调用一个函数的 Matlab 值或数据类型。在调用其它函数 时可以传递函数句柄,也可在数据结构中保存函数句柄备用。通过命令形式 fhandle = @functionname 可以创建函数句柄,例如 trigFun=@sin,或匿名函数 sqr = @(x) x.^2;。 使用句柄调用函数的形式是 fhandle(arg1, arg2, ..., argn) 或 fhandle()(无参数) 。 如: trigFun(1)。例: function x = plotFHandle(fhandle, data) plot(data, fhandle(data)) plotFHandle(@sin, -pi:0.01:pi) 数据类型转换如 C 语言中的强制类型转换相似 e.g.: y=9; z=double(y); Matlab 中的图像数据类型转换 MATLAB 中读入图像的数据类型是 uint8,而在矩阵中使用的数据类型是 double 因此 I2=im2double(I1) :把图像数组 I1 转换成 double 精度类型;如果不转换,在 对 uint8 进行加减时会产生溢出, 可能提示的错误为: Function '*' is not defined for values of class 'uint8'。 图像数据类型转换函数 默认情况下, matlab 将图像中的数据存储为 double 型, 即 64 位浮点数; matlab 还支持无符号整型(uint8 和 uint16) ;uint 型的优势在于节省空间,涉及运算时 要转换成 double 型。 im2double():将图像数组转换成 double 精度类型 im2uint8():将图像数组转换成 unit8 类型 im2uint16():将图像数组转换成 unit16 类型11.2 怎么在 matlab 自定义函数中再调用一个自定义函数?1、函数文件+调用函数文件:定义多个 M 文件: % 调用函数文件:myfile.m clear clc for t=1:10 y=mylfg(t); fprintf(‘M^(1/3)=%6.4f\n’,t,y); end %自定义函数文件: mylfg.m function y=mylfg(x) %注意:函数名(mylfg)必须与文件名(mylfg.m)一致 Y=x^(1/3); 注:这种方法要求自定义函数必须单独写一个 M 文件,不能与调用的命令文件 写在同一个 M 文件中。 2、函数文件+子函数:定义一个具有多个子函数的 M 文件 function y=average(x) %声明一个函数, y=average(x), 这个函数是取 x 的平均值, 返回值是 y y=mymean(x); %再次使用函数 mymean,此处该函数并没有定义算 法,而是在后面对其进行描述 function a=mymean(v) %定义函数 mymean,对于上级函数来说,此处为定义 子函数,进行函数嵌套 %a=mean(v); 可以自己写,如下句。 a=sum(v)/length(v); %此处为了简便, 使用内部求均值函数 mean, 当然也%对 v 求和并除以总长度可得其平均%注:自定义函数文件 funtry2.m 中可以定义多个子函数 function。子函数 lfg2 只 能被主函数和主函数中的其他子函数调用。11.3rand('state',sum(clock))是什么意思?首先要知道一点计算机生成的随机数都是伪随机数,当然 malab 也不例外 而这些伪随机数是怎样生成的呢?大多是用同余来生成 比如 x_n+1=(25173*x_n+13849) (mod 65536),而这些伪随机数都需要一个初值 x_0, 这样才能迭代 这个 x_0 就是此处的'state'参数,所以 rand('state',sum(clock))的作用是定义一个 随时间变化的初值 x_0。 作用: matlab 里面的随机生成函数基本都是以 rand 为基函数通过函数关系式得到,比 如 normrnd,unidrnd 等,你每次重启 matlab 后运行已编好的含随机数生成的函 数你将得到相同的结果,比如我的电脑上重启 matlab 运行 unidrnd(100),每次的 值都是 82,这是因为 rand 函数的初值都一样,所以为了避免上述问题经常在程 序前运行或加命令 rand('state',sum(clock)),这样重启 matlab,运行随机数生成值 就不同了。11.4inline 函数的用法在 matlab 命令窗口、程序或函数中创建局部函数时,可用 inline。优点是不必将 其储存为一个单独文件。在运用中有几点限制:不能调用另一个 inline 函数,只 能由一个 matlab 表达式组成, 并且只能返回一个变量---显然不允许[u,v]这种形式。 因而, 任何要求逻辑运算或乘法运算以求得最终结果的场合, 都不能应用 inline。 除了这些限制,在许多情况下使用该函数非常方便。 inline 这个 Matlab 程序怎么用? http://www.ilovematlab.cn/thread-.html (出处: MATLAB 中文论坛)11.512 机电系统控制12.1nyquist 曲线的绘制一、惯性环节的 nyquist 图形绘制 sys=1/Ts+1;令 T=1; matlab 仿真如下: sys=tf([1],[1 1]) nyquist(sys); grid;二、振荡环节系统传涵 sys=1/(T^2*s+2*zeta*T*s+1); matlab 仿真如下: num=[1]; T=1 for zeta=[0.6,0.7,0.9 ,1,1.1] sys=tf(num,[T,2*zeta*T 1]) nyquist(sys); legend('zeta=0.1','zeta=0.3','zeta=0.5','zeta=1','zeta=1.1') 仿真图形: 从图中可以看出当 zeta 增大时心形图案越小,幅值越小与用波特图画出的波形相对应。12.2 怎样画一半 nyquist 图?(ω 从 0 变到正无穷)运行后在 figure 图上点鼠标右键――点 show――去掉 negative frenquencies 前的 对号,就会只显示 0―正无穷的 nyquist 曲线。12.3 如 何 在 MATLAB 中 用 代 码 实 现 时 滞 / 延 时 环 节 (time delay)以实现为例:【方法 1】s=tf('s'); g1 = (s+1)/(s^2+s+1); g2 = exp(-s); g = g1*g2【方法 2】g=tf([1 1],[1 1 1],'ioDelay',1);以上两种方法的运行结果都是:Transfer function: s+1 exp(-1*s) * ----------s^2 + s + 1 单位阶跃响应曲线如下: 12.4 杂式% T=1 % for zeta=0.2:0.2:1 % % % end % % legend('zeta=0.2','zeta=0.4','zeta=0.6','zeta=0.8','zeta=1') % % G=tf(1,[1]) % % G.ioDelay=1 % % nyquist(G) sys=tf([1],[T,2*zeta*T 1]) nyquist(sys); % % % s=tf('s') % % % g1 = (s+1)/(s^2+s+1) % % % g2 = exp(-s) % % % g = g1*g2 num=[1] den=[1 1] H=tf(num,den) figure_bode=bode(H) t=[1:1:100]; axes(figure1) plot(t,-20*log(t)); xlim([0.1 10^2]);

我要回帖

更多关于 matlab中interp2函数 的文章

 

随机推荐