Assigning values to the arguments of a function handle

2 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

Star Strider
Star Strider am 22 Jan. 2024
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 Kommentare
Star Strider
Star Strider am 22 Jan. 2024
As always, my pleasure!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by