问题描述
考虑任意函数:
function myFunc_ = myFunc(firstInput,secondInput)
myFunc_ = firstInput * secondInput;
end
现在假设我想将上述函数映射到第一个输入 firstInput
的数组,而第二个输入 secondInput
是常量。例如,类似于:
firstvariable = linspace(0.,1.);
plot(firstvariable,map(myFunc,[firstvariable,0.1]))
其中 0.1
是 secondInput
的任意标量值,firstvariable
数组是 firstInput
的任意数组。
我研究了 arrayfun()
函数。但是,我不知道如何包含常量变量。另外,MATLAB 和 Octave 之间的语法似乎不同,或者我可能弄错了。拥有一个可以与同事共享的交叉兼容代码对我来说很重要。
解决方法
假设在原始函数中您将两个标量相乘并且您想进行矢量化,那么
function myFunc_ = myFunc(firstInput,secondInput)
myFunc_ = firstInput .* secondInput;
end
应该可以正常工作。
然后直接绘制:
plot( firstVariable,myFunc(firstVariable,0.1) )
,
恐怕原始问题中给出的任意示例过于简化,因此,它们并不代表我的代码面临的实际问题。但我确实设法找到了适用于 Octave 的正确语法:
plot(firstVariable,arrayfun(@(tempVariable) myFunc(tempVariable,0.1),firstVariable))
基本上是
@(tempVariable) myFunc(tempVariable,0.1)
创建所谓的匿名函数和
arrayfun(<function>,<array>)
将函数映射到给定数组上。