hyharry
hyharry

Reputation: 11

pass a matrix or vector to function handle in Matlab

everyone!

I've got a problem when using function handle in Matlab.

suppose I get a function handle of a transform matrix, say

Tf = @(alpha)reshape([cos(alpha),-sin(alpha),sin(alpha),cos(alpha)],[2,2]);

and I have a alpha vector

alpha_list = [alpha1; alpha2; ...];

I want to get the result like

[Tf1; Tf2; ...];

I have tried the ways like

Tf(alpha_list) feval(Tf,alpha_list) bsxfun(Tf,alpha_list)

They all don't work

Is there an easy or magic way to do this?

Many thanks!

Upvotes: 1

Views: 480

Answers (2)

user1543042
user1543042

Reputation: 3442

Edit:

Realized a way to make it faster and added explanation.

Using arrayfun allows you to apply the function tf to each element of the a individually.

It outputs as a cell array though so you need to convert it back to a matrix using cell2mat.

tf = @(alpha) [cos(alpha),sin(alpha);-sin(alpha),cos(alpha)];
Tf =@(a) cell2mat(arrayfun(@(A) tf(A), a, 'uni', 0));

so if you put in a 1xN vector you will get back a 2x2N matrix, if you put in a Nx1 vector you will get back a 2Nx2 matrix.

>> a = rand(2)

a =

     6.323592462254095e-01     2.784982188670484e-01
     9.754040499940953e-02     5.468815192049839e-01

>> Tf(a)

ans =

  Columns 1 through 3

     8.066353232983801e-01     5.910494524211303e-01     9.614693800974246e-01
    -5.910494524211303e-01     8.066353232983801e-01    -2.749120425428361e-01
     9.952467051120759e-01     9.738580986754016e-02     8.541503641387258e-01
    -9.738580986754016e-02     9.952467051120759e-01    -5.200261103460884e-01

  Column 4

     2.749120425428361e-01
     9.614693800974246e-01
     5.200261103460884e-01
     8.541503641387258e-01

>> Tf(a) - [tf(a(1,1)), tf(a(1,2)); tf(a(2,1)), tf(a(2,2))]

ans =

     0     0     0     0
     0     0     0     0
     0     0     0     0
     0     0     0     0

Upvotes: 2

GJStein
GJStein

Reputation: 658

Call Tfs for the solution:

Tf = @(a)[cos(a),sin(a); -sin(a), cos(a)];
Tfs = @(a) reshape(Tf(reshape(a,[1,1,length(a)])),[2,2*length(a)])'

The key here is that I use reshape to point the vector in the 3rd dimension, so that it doesn't interfere with the 2 we're interested in. Then we can use reshape again on the output which will preserve the block structure you're looking for.

This way, calling Tfs([1,2,2]) will return:

 0.5403    0.8415
-0.8415    0.5403
-0.4161    0.9093
-0.9093   -0.4161
-0.4161    0.9093
-0.9093   -0.4161

I should also point out that, if you're not concerned about speed very much, there are much simpler ways to do this using simple loops...

Edit: I switched the sign on Tf(a) because it was putting out Tf(a)'. It is correct now.

Upvotes: 1

Related Questions