How to vectorize a complex function?

3 ビュー (過去 30 日間)
Mohammad Shojaei Arani
Mohammad Shojaei Arani 2022 年 11 月 23 日
回答済み: Paul 2022 年 11 月 23 日
Hello,
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
g=@(par) nonbcon(par,J,N,X0,X,EZ,H,H_coeff,Coeff,knots,mesh_fine,M,SplineType,w);
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):
G=@(y)arrayfun(@(x) nonbcon(x),y(i,:));
but, I do not know how to modify G to do the job for me.
Any idea?
Thanks in advance!
Babak
  4 件のコメント
Torsten
Torsten 2022 年 11 月 23 日
This will error - a vector of function handles can only be defined as a cell array.
Mohammad Shojaei Arani
Mohammad Shojaei Arani 2022 年 11 月 23 日
OK. Thanks!
It seems that my only option is to use for-loop as this is not aparently paralaleisable

サインインしてコメントする。

回答 (1 件)

Paul
Paul 2022 年 11 月 23 日
Hi Babak,
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
rng(101);
test = rand(4,3);
sum(test,2)
ans = 4×1
1.9232 1.5945 0.8897 1.4173
Function that accepts a row vector and returns 0 or 1
g = @(par) double(sum(par,2)>1);
Loop solution
r1 = zeros(4,1);
for ii = 1:4,
r1(ii) = g(test(ii,:));
end
r1
r1 = 4×1
1 1 0 1
One line solution
r2 = cellfun(g,mat2cell(test,ones(size(test,1),1)))
r2 = 4×1
1 1 0 1

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by