2
votes

I have a function that accepts a matrix of dimension [1,2] and returns a matrix of dimensions [1,136]. I also have a matrix of dimensions [N,2]. I want to apply this function to each row of the matrix to finally get a matrix of dimensions [N,136].

I am completely lost on how to do this in Matlab. A for loop solution would be enough (I can't even do that at this point), but as far as I know in Matlab there are better and more parallelizable ways of doing things.

My current attempt looks like this:

  phi = arrayfun(@(x,y) gaussianBasis([x y])' , trainIn(:,1), trainIn(:,2), 'UniformOutput', false);

where gaussianBasis is a function returning a vector [136,1] and trainIn is a matrix [N,2]. phi is supposed to be [N,136], but this returns an array of N cell arrays each containing a matrix [1,136].

Thanks for all the help!

1
@yoda is spot on (+1). As you suggest in the question, it may also be possible to vectorize your function gaussianBasis to accept an N*2 input. If possible, this should run faster than the arrayfun approach, since arrayfun is often slower than an explicit loop. Of course, to determine if your function can be vectorized, we'd need to actually see it. Cheers.Colin T Bowers
Yoda's solution worked for me. I don't have to parallelize anything yet and I actually think I might have made a mistake while implementing gaussianBasis. OS maybe that will be my next question later. Thanks :).mck

1 Answers

4
votes

You just need to use cat and concatenate it along the first dimension:

phi = cat(1, phi{:})

This should give you an N x 136 matrix