如何将函数应用于Scilab中向量的每个元素?我正在寻找类似于Matlab的arrayfun()功能的东西。关于arrayfun()
:
B = arrayfun(func,A)
B = arrayfun(func,A)
将函数func应用于A的元素,一次一个元素。然后,arrayfun将func的输出连接到输出数组B,这样对于A的第i个元素B(i) = func(A(i))
。
答案 0 :(得分:3)
正如在另一个答案中所说,有时你可以简单地在一个函数中输入一个数组。但根据您的功能执行的操作,您可能会得到错误的结果。如果你想避免这种情况,你可以简单地定义自己的G:\PyScripts>python setup.py py2exe
running py2exe
Traceback (most recent call last):
File "setup.py", line 3, in <module>
setup(console=['cmd.py'])
File "C:\ProgramData\Anaconda3\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "C:\ProgramData\Anaconda3\lib\distutils\dist.py", line 955, in run_commands
self.run_command(cmd)
File "C:\ProgramData\Anaconda3\lib\distutils\dist.py", line 974, in run_command
cmd_obj.run()
File "C:\ProgramData\Anaconda3\lib\site-packages\py2exe\distutils_buildexe.py", line 188, in run
self._run()
File "C:\ProgramData\Anaconda3\lib\site-packages\py2exe\distutils_buildexe.py", line 267, in _run
builder.analyze()
File "C:\ProgramData\Anaconda3\lib\site-packages\py2exe\runtime.py", line 160, in analyze
self.mf.import_hook(modname)
File "C:\ProgramData\Anaconda3\lib\site-packages\py2exe\mf3.py", line 120, in import_hook
module = self._gcd_import(name)
File "C:\ProgramData\Anaconda3\lib\site-packages\py2exe\mf3.py", line 274, in _gcd_import
return self._find_and_load(name)
File "C:\ProgramData\Anaconda3\lib\site-packages\py2exe\mf3.py", line 357, in _find_and_load
self._scan_code(module.__code__, module)
File "C:\ProgramData\Anaconda3\lib\site-packages\py2exe\mf3.py", line 388, in _scan_code
for what, args in self._scan_opcodes(code):
File "C:\ProgramData\Anaconda3\lib\site-packages\py2exe\mf3.py", line 417, in _scan_opcodes
yield "store", (names[oparg],)
IndexError: tuple index out of range
,如下所示:
arrayfun
我称之为function B = matrixfun(func,A)
for i = 1 : size(A,'r')
for j = 1 : size(A,'c')
B(i,j) = func(A(i,j))
end
end
endfunction
,因为它更为通用。例如,考虑一个matrixfun
函数,它将实数toHex
转换为表示为十六进制的字符串。
x
您可以在控制台中查看结果:
--> disp(A) //original random matrix 37. 14. 4. 42. 17. 2. 18. 48. 23. 37. 31. 21. 16. 39. 43. 17. --> disp(B) //wrong results !5 14 4 10 ! ! ! !1 2 2 0 ! ! ! !7 5 15 5 ! ! ! !0 7 11 1 ! --> disp(C) //right results !25 E 4 2A ! ! ! !11 2 12 30 ! ! ! !17 25 1F 15 ! ! ! !10 27 2B 11 !