Я использую Octave и хотел бы векторизовать функцию, которая принимает в качестве входного единственного действительного числа и выводит вектор строки фиксированной длины. Я понимаю, что arrayfun
должен быть в состоянии сделать это из своей нечеткой документации. Из help arrayfun
в Octave 3.2:Функция векторизации, которая выводит строку с использованием arrayfun, возвращая матрицу
If the parameter VAL after a further string input argument "UniformOutput" is set 'true' (the default), then the named function FUNC must return a single element which then will be concatenated into the return value and is of type matrix. Otherwise, if that parameter is set to `false', then the outputs are concatenated in a cell array.
Кажется, однако, что Matlab's version is more forgiving:
[B1,...,Bm] = arrayfun(func,A1,...,An) calls the function specified by function handle func and passes elements from arrays A1,...,An, where n is the number of inputs to function func. Output arrays B1,...,Bm, where m is the number of outputs from function func, contain the combined outputs from the function calls. The ith iteration corresponds to the syntax [B1(i),...,Bm(i)] = func(A1{i},...,An{i}). The arrayfun function does not perform the calls to function func in a specific order.
Похоже, это работает в Matlab, но не в октаву. Правильно ли, что это обобщение не может быть выполнено с использованием arrayfun
в Octave? Есть ли еще более умный способ достичь этого, не прибегая к неветвированным петлям?
Для справки, вот мой Октав результат:
octave:5> nums
nums =@(c) ([c, c + 2, c + 4])
octave:6> arrayfun(nums,[1,2,3])
error: cellfun: expecting all values to be scalars for UniformOutput = true
error: called from:
error: /opt/local/share/octave/3.2.4/m/general/arrayfun.m at line 168, column 21
octave:6>
Почему вы настаиваете на 'arrayfun'? попробуйте простой цикл 'for' и сделайте с ним. – Shai
@Shai http://en.wikipedia.org/wiki/Vectorization_(parallel_computing) – djechlin
@djechlin: http://stackoverflow.com/questions/12522888/arrayfun-can-be-significantly-slower-than-an-explicit -loop-in-matlab-why – Daniel