Matlab/Octave中的向量/矩阵成员上的无环函数调用 [英] Loopless function calls on vector/matrix members in Matlab/Octave

查看:49
本文介绍了Matlab/Octave中的向量/矩阵成员上的无环函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从循环世界(C等)进入矩阵世界

I came into matrix world from loop world (C, etc)

我想在向量/矩阵的每个单独成员上调用一个函数,然后返回结果向量/矩阵.

I would like to call a function on each individual member of a vector/matrix, and return the resulting vector/matrix.

这是我目前的操作方式:

This is how I currently do it:

function retval = gauss(v, a, b, c)
  for i = 1:length(v)
    retval(i) = a*(e^(-(v(i)-b)*(v(i)-b)/(2*c*c)));
  endfor
endfunction

示例用法:

octave:47> d=[1:1000];
octave:48> mycurve=gauss(d, 1, 500, 100);

现在,关于MATLAB/Octave的所有建议都说:每当您发现自己使用循环并想出一种更好的方法时,就停止.

Now, all advice on MATLAB/Octave says: STOP whenever you catch yourself using loops and think of a better way of doing it.

因此,我的问题:是否可以在不使用显式循环的情况下一次调用向量/矩阵的每个成员上的函数,并将结果立即返回到新的向量/矩阵中?

那是我在寻找这样的东西:

That is I am looking for something like this:

 function retval = newfun(v)
    retval = 42*(v^23); 
endfunction

也许只是语法糖,仅此而已,但仍然有用.

Perhaps, it is just syntactic sugar, that is all, but still would be useful to know.

推荐答案

函数应如下所示:

function retval = gauss(v, a, b, c)
  retval = a*exp(-(v-b).^2/(2*c^2));

我建议您阅读有关如何向量化代码和避免循环的MATLAB文档:

I would recommend you to read MATLAB documentation on how to vectorize the code and avoid loops:

代码矢量化指南

提高性能的技术

还请记住,有时带有循环的代码可以比矢量化的代码更清晰,并且最近引入的JIT编译器MATLAB很好地处理了循环.

Also remember that sometime code with loops can be more clear that vectorized one, and with recent introduction of JIT compiler MATLAB deals with loops pretty well.

这篇关于Matlab/Octave中的向量/矩阵成员上的无环函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆