John
John

Reputation: 5913

Matlab outer product like function? How?

I have the following computation I'd like to vectorize in matlab.

I have a N x 3 array, call it a. I have a 4 x 1 cell array of function handles, call them b.

I would like to create an Nx4 matrix c, such that c(i,j) = b{j}(a(i,:).

b is actually an array, but I don't know how to write down my representation for c in a format that matlab would understand that uses a matrix.

Upvotes: 3

Views: 1125

Answers (2)

John
John

Reputation: 5913

pdist2 almost solves the problem above. Probably someone more clever than me can figure out how to shoe horn the two together.

Upvotes: 1

Jonas
Jonas

Reputation: 74940

If your function handles work on arrays (i.e. b{j}(a) returns a Nx1 array in your example), you can use CELLFUN and CELL2MAT to generate your output array:

c = cell2mat( cellfun( @(bFun)bFun(a),b,'UniformOutput',false) );

If your function handles only work on individual rows (i.e. b{j} needs to be applied to every row of a separately, you can throw ARRAYFUN into the mix (readability suffers a bit though; basically, you're applying each element of b via cellfun to each row of a via arrayfun):

c = cell2mat(...
       cellfun( @(bFun)arrayfun(...
            @(row)bFun(a(row,:)),1:size(a,1)),...
       b,'UniformOutput',false) ...
    );

Upvotes: 3

Related Questions