matlab - Efficient way to apply arrayfun to a matrix (i.e. R^N to R^M) -
i have function transforms r^n r^m. simplicity, lets let identity function @(z) z
z may vector. want apply function list of parameters of size k x n
, have map k x m
output.
here attempt:
function out_matrix = array_fun_matrix(f, vals) i=1:size(vals,1) f_val = f(vals(i,:)); if(size(f_val,1) > 1) %need stack rows, convert required. f_val = f_val'; end out_matrix(i,:) = f_val; end end
you can try with
array_fun_matrix(@(z) z(1)^2 + z(2)^2 + z(3), [0 1 0; 1 1 1; 1 2 1; 2 2 2])
the question: there better , more efficient way vectorization, etc.? did miss built-in function?
examples of non-vectorizable functions: there many, involving elaborate sub-steps , numerical solutions. trivial example looking numerical solution equation, in term using numerical quadrature. i.e. let params = [b c]
, solve a
such int_0^a ((z + b)^2) dz = c
(i know here calculus, integral here stripped down). implementing example,
find_equilibrium = @(param) fzero(@(a) integral(@(x) (x + param(1)).^2 - param(2), 0, a), 1) array_fun_matrix(find_equilibrium, [0 1; 0 .8])
you can use cellfun
function, you'll need manipulate data bit:
function out_matrix = array_fun_matrix(f, vals) % convert data cell array: cellvals = mat2cell(vals, ones(1,size(vals,1))); % apply function: out_cellarray = cellfun(f, cellvals, 'uniformoutput', false); % convert matrix: out_matrix = cell2mat(out_cellarray); end
if don't implementation, can improve performance of yours preallocating out_matrix:
function out_matrix = array_fun_matrix(f, vals) firstoutput = f(vals(1,:)); out_matrix = zeros(size(vals,1), length(firstoutput)); % preallocate speed. i=1:size(vals,1) f_val = f(vals(i,:)); if(size(f_val,1) > 1) %need stack rows, convert required. f_val = f_val'; end out_matrix(i,:) = f_val; end end
Comments
Post a Comment