Assigning values to the arguments of a function handle

2 ビュー (過去 30 日間)
Mohammad Shojaei Arani
Mohammad Shojaei Arani 2024 年 1 月 22 日
コメント済み: Star Strider 2024 年 1 月 22 日
Hello,
I have the following functon handle
F = @(x1,x2,x3,a1_1,a1_2,a1_3,a2_1,a2_2,a2_3,a3_1,a3_2,a3_3,r1,r2,r3)[-r1.*x1.*(a1_1.*x1+a1_2.*x2+a1_3.*x3-1.0);-r2.*x2.*(a2_1.*x1+a2_2.*x2+a2_3.*x3-1.0);-r3.*x3.*(a3_1.*x1+a3_2.*x2+a3_3.*x3-1.0)]
where a = [a_ij] is a matrix, r = [r_ij] is a column vector and x1, x2,x3 are columns of the matrix x = [x1 x2 x3]. The output should be a matrix whose size is the same as x. To make things easier, let's assume that
a = [1 2 3;4 5 6;7 8 9]; r =[1;2;3]; x = ones(10,3);
I need to calculate F(x, a, r) in a fast way. A naive aproach is to calculate F for each row of x in a for-loop which is very time consumming. But, I am struggling on how to do this in a vectorized manner.
Thanks for your help in advance!
best,
Babak

採用された回答

Star Strider
Star Strider 2024 年 1 月 22 日
Again, using numbered variables as not considered good programming practise.
I believe this correspoinds to your original code.
Try this —
F = @(x,a,r)[-r(1).*x(:,1).*(a(1,:)*x-1.0); -r(2).*x(:,2).*(a(2,:)*x-1.0); -r(3).*x(:,3).*(a(3,:)*x-1.0)];
F = function_handle with value:
@(x,a,r)[-r(1).*x(:,1).*(a(1,:)*x-1.0);-r(2).*x(:,2).*(a(2,:)*x-1.0);-r(3).*x(:,3).*(a(3,:)*x-1.0)]
a = [1 2 3;4 5 6;7 8 9];
r =[1;2;3];
x = ones(10,3);
Result = F(a,x,r)
Result = 9×3
-11 -14 -17 -44 -56 -68 -77 -98 -119 -44 -56 -68 -110 -140 -170 -176 -224 -272 -99 -126 -153 -198 -252 -306 -297 -378 -459
Does this do what you want?
Note that it uses straightforward array indexing.
.
  7 件のコメント
Mohammad Shojaei Arani
Mohammad Shojaei Arani 2024 年 1 月 22 日
Thanks Star!
Star Strider
Star Strider 2024 年 1 月 22 日
As always, my pleasure!

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

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by