How to vectorize a complex function?
4 views (last 30 days)
I have a rather complex function but I need to vectorize it in order to be able to use a matlab optimization package. My function is
You do not need to know the details of this function. g, accepts a row vector "par" and then as output gives either 0 or 1. However, I need to vectorize g so that it accepts a matrix A and performs the same operation on each row of A. I tried to use arrayfun but it is a bit complicated for me. I need something like the following (of course, this is wrong):
but, I do not know how to modify G to do the job for me.
Thanks in advance!
Paul on 23 Nov 2022
Here is a one line solution. Whether or not it's more efficient/effective/clearer than the loop is an open question.
Test data for input
test = rand(4,3);
Function that accepts a row vector and returns 0 or 1
g = @(par) double(sum(par,2)>1);
r1 = zeros(4,1);
for ii = 1:4,
r1(ii) = g(test(ii,:));
One line solution
r2 = cellfun(g,mat2cell(test,ones(size(test,1),1)))