你最喜欢的 MATLAB/Octave 编程技巧是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/132092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 16:39:06  来源:igfitidea点击:

What is your favourite MATLAB/Octave programming trick?

matlaboctave

提问by Matt

I think everyone would agree that the MATLAB language is not pretty, or particularly consistent. But nevermind! We still have to use it to get things done.

我想每个人都会同意 MATLAB 语言不漂亮,或者特别一致。但是不要紧!我们仍然必须使用它来完成工作。

What are your favourite tricks for making things easier? Let's have one per answer so people can vote them up if they agree. Also, try to illustrate your answer with an example.

你最喜欢的让事情变得更容易的技巧是什么?让我们每个答案都有一个,这样人们就可以在他们同意的情况下投票。另外,试着用一个例子来说明你的答案。

回答by Jason Sundram

Using the built-in profiler to see where the hot parts of my code are:

使用内置分析器查看我的代码的热门部分在哪里:

profile on
% some lines of code
profile off
profile viewer

or just using the built in ticand tocto get quick timings:

或者只是使用内置的tictoc获得快速计时:

tic;
% some lines of code
toc;

回答by sundar - Reinstate Monica

Directly extracting the elements of a matrix that satisfy a particular condition, using logical arrays:

使用逻辑数组直接提取满足特定条件的矩阵元素:

x = rand(1,50) .* 100;
xpart = x( x > 20 & x < 35);

Now xpart contains only those elements of x which lie in the specified range.

现在 xpart 只包含位于指定范围内的 x 元素。

回答by Scottie T

Provide quick access to other function documentation by adding a "SEE ALSO" line to the help comments. First, you must include the name of the function in all caps as the first comment line. Do your usual comment header stuff, then put SEE ALSO with a comma separated list of other related functions.

通过在帮助注释中添加“SEE ALSO”行,提供对其他功能文档的快速访问。首先,您必须在所有大写中包含函数名称作为第一个注释行。做你通常的评论标题的东西,然后用逗号分隔的其他相关函数列表把 SEE ALSO 放在一起。

function y = transmog(x)
%TRANSMOG Transmogrifies a matrix X using reverse orthogonal eigenvectors
%
% Usage:
%   y = transmog(x)
%
% SEE ALSO
% UNTRANSMOG, TRANSMOG2

When you type "help transmog" at the command line, you will see all the comments in this comment header, with hyperlinks to the comment headers for the other functions listed.

当您在命令行键入“help transmog”时,您将看到此注释标题中的所有注释,以及指向列出的其他功能的注释标题的超链接。

回答by Scottie T

Turn a matrix into a vector using a single colon.

使用单个冒号将矩阵转换为向量。

x = rand(4,4);
x(:)

回答by Jason Sundram

Vectorizing loops. There are lots of ways to do this, and it is entertaining to look for loops in your code and see how they can be vectorized. The performance is astonishingly faster with vector operations!

向量化循环。有很多方法可以做到这一点,在您的代码中查找循环并查看如何将它们矢量化是很有趣的。向量运算的性能惊人地快!

回答by Jason S

Anonymous functions, for a few reasons:

匿名函数,有几个原因:

  1. to make a quick function for one-off uses, like 3x^2+2x+7. (see listing below) This is useful for functions like quadand fminbndthat take functions as arguments. It's also convenient in scripts (.m files that don't start with a function header) since unlike true functions you can't include subfunctions.
  2. for closures-- although anonymous functions are a little limiting as there doesn't seem to be a way to have assignment within them to mutate state.
  1. 为一次性使用创建快速函数,例如 3x^2+2x+7。(见下面的列表)这对于像这样的函数很有用,quad并且fminbnd将函数作为参数。它在脚本(不以函数头开头的 .m 文件)中也很方便,因为与真正的函数不同,您不能包含子函数。
  2. 对于闭包——尽管匿名函数有点限制,因为似乎没有办法在它们内部赋值来改变状态。

.

.

% quick functions
f = @(x) 3*x.^2 + 2*x + 7;
t = (0:0.001:1);
plot(t,f(t),t,f(2*t),t,f(3*t));

% closures (linfunc below is a function that returns a function,
% and the outer functions arguments are held for the lifetime
% of the returned function.
linfunc = @(m,b) @(x) m*x+b;
C2F = linfunc(9/5, 32);
F2C = linfunc(5/9, -32*5/9);

回答by ymihere

Matlab's bsxfun, arrayfun, cellfun, and structfunare quite interesting and often save a loop.

Matlab 的bsxfunarrayfuncellfunstructfun非常有趣,而且经常保存一个循环。

M = rand(1000, 1000);
v = rand(1000,    1);
c = bsxfun(@plus, M, v);

This code, for instance, adds column-vector v to each column of matrix M.

例如,此代码将列向量 v 添加到矩阵 M 的每一列。

Though, in performance critical parts of your application you should benchmark these functions versus the trivial for-loop because often loops are still faster.

但是,在应用程序的性能关键部分,您应该对这些函数进行基准测试,而不是简单的 for 循环,因为通常循环仍然更快。

回答by Jason S

LaTeX mode for formulas in graphs: In one of the recent releases (R2006?) you add the additional arguments ,'Interpreter','latex'at the end of a function call and it will use LaTeX rendering. Here's an example:

图形中公式的 LaTeX 模式:在最近的一个版本 (R2006?) 中,您,'Interpreter','latex'在函数调用的末尾添加了额外的参数,它将使用 LaTeX 渲染。下面是一个例子:

t=(0:0.001:1);
plot(t,sin(2*pi*[t ; t+0.25]));
xlabel('t'); 
ylabel('$\hat{y}_k=sin 2\pi (t+{k \over 4})$','Interpreter','latex');
legend({'$\hat{y}_0$','$\hat{y}_1$'},'Interpreter','latex');

Not sure when they added it, but it works with R2006b in the text(), title(), xlabel(), ylabel(), zlabel(), and even legend() functions. Just make sure the syntax you are using is not ambiguous (so with legend() you need to specify the strings as a cell array).

不确定他们何时添加它,但它在 text()、title()、xlabel()、ylabel()、zlabel() 甚至 Legend() 函数中与 R2006b 一起使用。只要确保您使用的语法没有歧义(因此使用 legend() 您需要将字符串指定为元胞数组)。

回答by Samil

Using xlim and ylim to draw vertical and horizontal lines. Examples:

使用 xlim 和 ylim 绘制垂直和水平线。例子:

  1. Draw a horizontal line at y=10:

    line(xlim, [10 10])

  2. Draw vertical line at x=5:

    line([5 5], ylim)

  1. 在 y=10 处画一条水平线:

    line(xlim, [10 10])

  2. 在 x=5 处绘制垂直线:

    line([5 5], ylim)

回答by Matt

Here's a quick example:

这是一个快速示例:

I find the comma separated list syntax quite useful for building function calls:

我发现逗号分隔的列表语法对于构建函数调用非常有用:

% Build a list of args, like so:
args = {'a', 1, 'b', 2};
% Then expand this into arguments:
output = func(args{:})