百科问答小站 logo
百科问答小站 font logo



有哪些让人相见恨晚的 MATLAB 命令? 第1页

  

user avatar   leng-zhe 网友的相关建议: 
      

Matlab里面应该多用向量运算,把循环语句转变为向量运算会省很多时间,程序也更简洁易读。

比方说,一个名叫array数组里面,你要将里面大于1的都变成0,就不必用到循环:

array(array>1)=0;

把大于1小于3的变成0。

array(and(array>1,array<3))=0;

当然,还可以使用find,这个也很好用。

——————————————————————————————

另一个重要的技巧是delete/clf-plot-pause

用plot可以画图(注意记录句柄),然后用delete删掉特定图象,或用clf清图,再绘制,这可以在figure窗口产生动画。但是如果只plot,往往只会在全部程序执行结束时显示,这时候需要用pause让figure完成图像的更新。drawnow貌似也可以,但是我比较喜欢用pause,能够简单地控制动画的速度。

这会方便调试和展示。这个技巧尤其适合使用matlab的图形用户界面设计功能时构造一个显示运行状态等信息的figure。

——————————————————————————————

mathworks 有一个fig函数(不是系统自带的,是别人编写的),可以很容易地调整字体、尺寸以及绘图是否有边框等等,不必画出来再自己手动调整。这对于写论文的人来说会很方便。

这些年有太多人向我要这个文件了,我把程序贴在回答的最后了,大家自己用吧。

——————————————————————————————

善用eval,可以让你的程序的灵活度大大加强。尤其是在变量名的问题上。当然,这可能会对代码维护和调试带来麻烦。很多情况可以用其他方法代替。 @王备 指出了一个链接,值得一读Alternatives to the eval Function

——————————————————————————————

save、load可以将部分或全部变量、结构体等存入mat文件或从mat导入workspace

global可以将变量变为全局变量,在各函数之间共享。不过这不太好用,尽量慎用吧。

——————————————————————————————

exist可以检测某目标(如变量)是否存在,减少一些麻烦。

——————————————————————————————

surf、mesh都很漂亮,不过surf之后记得用shading interp,看起来更漂亮。

——————————————————————————————

对于一些重复性的矩阵赋值,比如:1、2、3、4、1、2、3、4

可以使用repmat,将一个矩阵重复扩展为更大的矩阵。

——————————————————————————————

很多函数都有高级的用法,当使用到了,但又觉得有点麻烦的时候,不妨help一下,看看其他的用法。

总而言之,还是多上网搜索,一般问题总有很好的答案。


——————————————————————————

最后把fig文件贴在这里

       function h = fig(varargin) % FIG - Creates a figure with a desired size, no white-space, and several other options. % %       All Matlab figure options are accepted.  %       FIG-specific options of the form FIG('PropertyName',propertyvalue,...)  %       can be used to modify the default behavior, as follows: % %       -'units'    : preferred unit for the width and height of the figure  %                      e.g. 'inches', 'centimeters', 'pixels', 'points', 'characters', 'normalized'  %                      Default is 'centimeters' % %       -'width'    : width of the figure in units defined by 'units' %                      Default is 14 centimeters %                      Note: For IEEE journals, one column wide standard is %                      8.5cm (3.5in), and two-column width standard is 17cm (7 1/16 in) % %       -'height'   : height of the figure in units defined by 'units' %                      Specifying only one dimension sets the other dimension %                      to preserve the figure's default aspect ratio.  % %       -'font'     : The font name for all the texts on the figure, including labels, title, legend, colorbar, etc. %                      Default is 'Times New Roman'  % %       -'fontsize' : The font size for all the texts on the figure, including labels, title, legend, colorbar, etc. %                      Default is 14pt %        %       -'border'   : Thin white border around the figure (compatible with export_fig -nocrop)  %                      'on', 'off' %                      Default is 'off'  % %   FIG(H) makes H the current figure.  %   If figure H does not exist, and H is an integer, a new figure is created with %   handle H. % %   FIG(H,...) applies the properties to the figure H. % %   H = FIG(...) returns the handle to the figure created by FIG. % % % Example 1: %   fig % % Example 2: %   h=fig('units','inches','width',7,'height',2,'font','Helvetica','fontsize',16) % % % Copyright  ?2012 Reza Shirvany,  matlab.sciences@neverbox.com  % Source:   http://www.mathworks.com/matlabcentral/fileexchange/30736 % Updated:   05/14/2012 % Version:   1.6.5  % %Revised by Zhe Leng 2012 Jul 10th, add set(H, 'PaperPositionMode', %'auto'); for consistency in the saved images files.        % default arguments width=14; font='Times New Roman'; fontsize=14;  units='centimeters'; bgcolor='w'; sborder='off'; flag=''; Pindex=[];  %%%%%%%%%%% process optional arguments optargin = size(varargin,2); if optargin>0  % check if a handle is passed in if isscalar(varargin{1}) && isnumeric(varargin{1})     flag=[flag '1'];     i=2;      if ishghandle(varargin{1})==1         flag=[flag 'i'];     end else     i=1; end  % get the property values while (i <= optargin)     if (strcmpi(varargin{i}, 'border'))         if (i >= optargin)             error('Property value required for: %s', num2str(varargin{i}));         else             sborder = varargin{i+1};flag=[flag 'b'];             i = i + 2;         end     elseif (strcmpi(varargin{i}, 'width'))         if (i >= optargin)             error('Property value required for: %s', num2str(varargin{i}));         else             width = varargin{i+1};flag=[flag 'w'];             i = i + 2;         end     elseif (strcmpi(varargin{i}, 'height'))         if (i >= optargin)             error('Property value required for: %s', num2str(varargin{i}));         else             height = varargin{i+1};flag=[flag 'h'];             i = i + 2;         end     elseif (strcmpi(varargin{i}, 'font'))         if (i >= optargin)             error('Property value required for: %s', num2str(varargin{i}));         else             font = varargin{i+1};flag=[flag 'f'];             i = i + 2;         end     elseif (strcmpi(varargin{i}, 'fontsize'))         if (i >= optargin)             error('Property value required for: %s', num2str(varargin{i}));         else            fontsize = varargin{i+1};flag=[flag 's'];             i = i + 2;         end     elseif (strcmpi(varargin{i}, 'units'))         if (i >= optargin)             error('Property value required for: %s', num2str(varargin{i}));         else             units = varargin{i+1};flag=[flag 'u'];             i = i + 2;         end     elseif (strcmpi(varargin{i}, 'color'))         if (i >= optargin)             error('Property value required for: %s', num2str(varargin{i}));         else             bgcolor = varargin{i+1};flag=[flag 'c'];             i = i + 2;         end     else         %other figure properties         if (i >= optargin)             error('A property value is missing.');         else         Pindex = [Pindex i i+1];         i = i + 2;         end     end  end  end  % We use try/catch to handle errors try  % creat a figure with a given (or new) handle if length(strfind(flag,'1'))==1     s=varargin{1};     if ishandle(s)==1     set(0, 'CurrentFigure', s);     else          figure(s);     end else     s=figure; end  flag=[flag 's'];  % set other figure properties if ~isempty(Pindex)     set(s,varargin{Pindex}); end  % set the background color set(s, 'color',bgcolor);  % set the font and font size set(s, 'DefaultTextFontSize', fontsize);  set(s, 'DefaultAxesFontSize', fontsize);  set(s, 'DefaultAxesFontName', font); set(s, 'DefaultTextFontName', font);  %%%%%%%%%%% set the figure size % set the root unit old_units=get(0,'Units'); set(0,'Units',units);  % get the screen size scrsz = get(0,'ScreenSize');  % set the root unit to its default value set(0,'Units',old_units);  % set the figure unit set(s,'Units',units);  set(s, 'PaperPositionMode', 'auto');  % get the figure's position pos = get(s, 'Position'); old_pos=pos; aspectRatio = pos(3)/pos(4);  % set the width and height of the figure if length(strfind(flag,'w'))==1 && length(strfind(flag,'h'))==1      pos(3)=width;     pos(4)=height; elseif isempty(strfind(flag,'h'))     pos(3)=width;     pos(4) = width/aspectRatio; elseif isempty(strfind(flag,'w')) && length(strfind(flag,'h'))==1     pos(4)=height;     pos(3)=height*aspectRatio;  end  % make sure the figure stays in the middle of the screen diff=old_pos-pos;   if diff(3)<0  pos(1)=old_pos(1)+diff(3)/2;      if pos(1)<0          pos(1)=0;      end  end  if diff(4)<0  pos(2)=old_pos(2)+diff(4);     if pos(2)<0          pos(2)=0;      end  end   % warning if the given width (or height) is greater than the screen size if pos(3)>scrsz(3) warning(['Maximum width (screen width) is reached! width=' num2str(scrsz(3)) ' ' units]); end  if pos(4)>scrsz(4) warning(['Maximum height (screen height) is reached! height=' num2str(scrsz(4)) ' ' units]); end  % apply the width, height, and position to the figure set(s, 'Position', pos); if strcmpi(sborder, 'off')     set(s,'DefaultAxesLooseInset',[0,0,0,0]); end        % handle errors catch ME     if isempty(strfind(flag,'i')) && ~isempty(strfind(flag,'s'))     close(s);     end    error(ME.message) end  s=figure(s); % return handle if caller requested it.   if (nargout > 0)         h =s;   end % % That's all folks! % %flag/1iwhfsucsb      

用法是这样:

你可以先用fig生成一个画图窗口(同时设置其显示方式),然后再用plot画。

也可以用h=fig(……)来生成一个画图窗口并获得其句柄,然后后续用plot(h,……)来画图

还可以用H=plot(……)来画图,然后用fig(H,……)来设置一个已经存在的画图窗口的显示方式。


user avatar   zhen-tan-83 网友的相关建议: 
      
  • 1.对两路信号作图时,可用 linkaxes 同步x轴,以便之后手动放大同步查看局部细节,例如:
       ax(1) = subplot(2,1,1) plot(time,signal1) ax(2) = subplot(2,1,2) plot(time,signal2)    linkaxes (ax,'x')      

当然你也可以同步y轴:linkaxes (ax,'y') ,甚至两轴都同步:linkaxes (ax,'xy') 。


--------- 更新1---------

  • 2. 相信很多人都知道hold on指令能用于作重叠的曲线图,但当两曲线值域相差太大时,以至于不能更好地展示彼此的细节,可考虑用如下方法(MATLAB 2016a 开始支持,低版本的用plotyy):
       plot(time,signal1) yyaxis right      % 用右边的y轴展示 plot(time,signal2)     

偷一张MATLAB官网的图来展示一下效果(侵删)。此方法跟前面的linkaxes有些相似,然而linkaxes能展示多个曲线。linkaxes适合用于自己查看分析,本方法适合作报告节省空间。


  • 3.很多人提到多行注释 ctrl + R 。但其缺点是不能折叠。利用如下格式,可使注释后的内容折叠起来。
                %{          可折叠的注释区域          %}            

--------- 更新2---------

  • 4. 获取当前路径:path = pwd; 。获取当前路径所有文件及文件夹的名字:names = ls ;其实要想具体一点,用dir代替ls会更好:files = dir;

--------- 更新3---------

  • 5. 用 deal() 让初始化更简洁。

合并内容相同的初始化:

       % 假如要初始化A,B,C和D为3*4阶矩阵,平常我们会用如下代码 A = zeros(3,4); B = zeros(3,4); C = zeros(3,4); D = zeros(3,4);  % 利用deal()改造后,简洁相当多 [A,B,C,D] = deal(zeros(3,4));     

当然,初始化的内容不一定都相同,但是仍然可以缩成一行

       % 如以下例子 A = zeros(3,4); B = []; C = ones(2); D = cell(2);  % 可以用deal()改造,只是长一点 [A,B,C,D] = deal(zeros(3,4),[],ones(2),cell(2));     

初始化结构体数组,当行数特别多时,优势明显

       % 正常方法初始化3行,两个field的结构体数组: inl = {0, 0, 0};  % 必须得元胞数组,有些麻烦 s = struct('f1',inl,'f2',inl);  % 用deal改进 [s(1:3).f1,s(1:3).f2] = deal(0);  % 如果内容不一样,就每个field分开来 [s(1:3).f1] = deal(0); [s(1:3).f2] = deal(zeros(3));  % 把3改成任意行数n     

--------- 更新4---------

  • 6. 大家觉不觉得每次用plot作图返回的窗口都好小,每次都要手动按右上角的框框放大,贼烦~以下命令实现自动放大
       % 以下代码实现自动放大 fig = figure; fig.Position = get(0,'ScreenSize');  % fig.Position这种操作好像MATLAB 2012还是2013之后才有的,忘记了,低版本用set吧 % % % % 我是分界线 % % % % plot(1:10)  % 随便做个图查看效果 zoom on  % 顺手加个放大,省得点工具栏     

--------- 更新5---------

  • 7. 这个可能很多人知道,但是真的很好用。用‘end’检索最后一位元素
       % 正常方法获取向量V最后一位元素 N = length(V); last = V(N);  % 用end的话方便很多 last = V(end);  % 还可以这样 test1 = V(end-1);   % 倒数第二个 test2  = V(1:end/2);  % 获取一半(奇数长度会有警告)     

矩阵的用法差不多,就不举例了


  • 8. 前面有人说过 dbstop if error。如果再配合两把宝剑,会更好用:dbup 和 dbdown。

这两个命令在程序错误并断点之后在命令行输入,用于在workspace间切换查看变量调试。dbup是跳到上层workspace,dbdown是返回。




  

相关话题

  有哪些计算机术语的翻译,让你第一次学的时候感到十分别扭? 
  为什么 Python(或 Ruby、Perl 等)没有取代 Bash 成为系统 Shell? 
  c#匿名委托获取自身的方法? 
  中国计算机专业的大学生相比于美国差在哪里? 
  有哪些让你浑身颤抖、无法自拔,庆幸读到的好书? 
  为什么总有一些人推荐计算机学生把重点放在高数和线代? 
  有哪些错位的古诗词句,显得无比协调? 
  有哪些自以为很懂你兴趣圈的人做过的令你不适的事? 
  有哪些有趣的妖魔鬼怪或者神仙? 
  开源与共产主义的本质区别是什么? 

前一个讨论
为什么民航客机几乎都没有装备反导系统?
下一个讨论
为什么有时桃肉还新鲜而桃核已发霉?





© 2024-05-21 - tinynew.org. All Rights Reserved.
© 2024-05-21 - tinynew.org. 保留所有权利