matlab到R:函数调用和@ [英] matlab to R: function calling and @

查看:195
本文介绍了matlab到R:函数调用和@的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 R ,但我正在将代码从matlab转换为 R

我的研究表明, @ 可以让你调用一个函数通过固定变量的另一个名称,例如

  g = @(b)f(a1,b,c1)

允许我调用 f ,只指定 b 通过做 g(b)



在我使用的代码中是函数

pre $ code>函数dN = WW(N,h,A,P,aA,aP,bA,bP)

在代码中的某处出现 WW 是称为,但是用

  f = @(t,N)调用WW(N,h,A,P,aA, aP,bA,bP)

为什么我很困惑: t,在代码中没有其他地方提及N ,但 h,A,P,aA,aP,bA,bP 。



没有人认识到这个结构和可能发生的事情吗?

你说得对您对 @ 的评估。 @(t)就是所谓的匿名函数。因此, @(t)将返回一个句柄给一个函数,该函数接受一个变量 t 。基本上,它是一个函数,它接受一个参数 t 。其余的参数先前在工作区中定义。

举例来说,您的 g = @(b)f(a1,b,c1)的陈述允许你将这个函数调用封装到另一个名为 g a1 c1 先前在您的工作区中定义。因此这个函数将依赖一个进入函数的变量,它是 b 。因此,当您调用函数 g 时,这些参数将保持静态,并且可以即时更改 b 。换句话说,每次调用 g a1 c1 b 会根据您放入 g 而改变>(检查词汇范围)。显然,如果在你的工作区中改变 a1 c1 ,那么当你调用 g 下一次。



现在,用其他函数调用。 t 永远不会被使用,但 N 是!因此, N 会在您更改时动态更改,但是 t 对该函数句柄˚F。不管你如何改变 t f 的输出将是相同的,只要你不改变 N



无论如何,您的评估确实是正确的。


I use R but I am translating code from matlab to R. I have reached a section which I cannot grok.

My research shows that the @ allows you to call a function by another name with fixed variables e.g.

g = @(b) f(a1, b, c1)

allows me to call f only specifying b by doing g(b)

In the code I am working with there is a function

function dN = WW(N,h,A,P,aA,aP,bA,bP)

at some point in the code it appears WW is called, but is called with

f = @(t,N) WW(N,h,A,P,aA,aP,bA,bP)

Why I am so confused is that t,N are mentioned nowhere else in the code....but h,A,P,aA,aP,bA,bP are all defined prior.

does anyone recognise this structure and what might be going on?

解决方案

You are correct in your assessment of @. @(t) is what is known as an anonymous function. @(t) will thus return a handle to a function that takes in one variable t. Basically, it's a function that takes in one parameter, t. The rest of the parameters are defined previously in your workspace.

As an example, your statement of g = @(b) f(a1, b, c1) allows you to encapsulate this function call into another function called g, and a1 and c1 are previously defined in your workspace. This function will thus rely on one variable that goes into the function, which is b. As such, these parameters will remain static when you call the function g, and you can change b on the fly. In other words, every time you call g, a1 and c1 will always stay the same while b will change depending on what you put into g (check out Lexical Scope). Obviously, should a1 and c1 change in your workspace, this behaviour will be reflected when you call g the next time as well.

Now, with the other function call. t is never used, but N is! As such, N will dynamically change when you vary it, but t will have no effect on that function handle of f. No matter how you vary t, the output of f will be the same, provided that you don't change N!

In any case, your assessment is indeed correct.

这篇关于matlab到R:函数调用和@的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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