Is it possible in MATLAB to create a 3D array from a function which returns 2D arrays without using a loop? -
i have matlab function f(w) returns (n x n) square matrix. have vector ws = [w_1, w_2, ... w_m] contains m parameters w_i. create 3d array contains m "planes" f(w_i). possible in matlab using arrayfun() et al. create 3d array without using for loops iterate on parameter vector ws , concatenating results?
if want see how few functions can used, here's approach arrayfun, cell2mat , reshape combined (i changed last line according daniel's comment):
f = @(w) [w 2*w; 3*w 4*w]; %// random function returns array of fixed size w = 1:4; %// random input function out = cell2mat(reshape(arrayfun(@(x) f(w(x)), w, 'uniformoutput', 0),1,1,[])); you (probably fastest of these approaches, there faster approaches):
out = f(reshape(w,1,1,[])) or use loop (notice order of loop):
for ii = numel(w):-1:1 out(:,:,ii) = f(w(ii)); %// no pre-allocation necessary end or more traditional loop approach:
out = zeros(2,2,4); %// pre-allocation necessary ii = 1:numel(w) out(:,:,ii) = f(w(ii)); end i go on, think you've have few @ here...
Comments
Post a Comment