Using cell array to define Argument list in function Handle

4 views (last 30 days)
Hello, I have a function handle like this:
Q= @(rho1,rho2,rho3,rho4) Q0 + Q1*rho1 + Q2*rho2 + Q3*rho3 + Q4*rho4;
Here I am manually entering rho1,...,rho4. I have several function handle like this in my code. My argument list is not limited to just 4 but it can be very big like rho1,.....,rho50. Hence I would like to avoid entering it like this, because code becomes unreadable with big list and also changing each time is not desirable. So, I have collected names of each argument in a cell array
test ={};
for h=1:4
>> test
test =
1×4 cell array
{'rho1'} {'rho2'} {'rho3'} {'rho4'}
When I try to use this 'test' in argument list like this:
Rq= @(test) Q0 + Q1*rho1 + Q2*rho2 + Q3*rho3 + Q4*rho4;
I get an error that there are too many input arguemnt. Its also showing me the error in some other function in my code. Is the way I am giving my arglist is wrong here? Could someone clarify?

Answers (1)

Matt J
Matt J on 15 Jan 2020
Edited: Matt J on 15 Jan 2020
That is not the right approach. You should be taking advantage of the fact that this is Matlab, and that your variables are allowed to be vectors and matrices. Assuming your Q0,Q1,... and rho0, rho1,... are all scalars, you could be writing your function this way,
Q= @(rhoVector) Qvector*rhoVector.';
You should also be using vectorized commands to create these vectors. You should not be creating Q0,Q1, etc... one element at a time.
Matt J
Matt J on 15 Jan 2020
Edited: Matt J on 15 Jan 2020
Well, we would have to see how general your function is. For an M-term generalization of what you've shown, you would have your Q's in an NxNxM array called, say Qarray, and your rho exponents in an M-vector, e, and do something like this
Q =@(rho) reshape( reshape(Qarray,[],M)*rho(:).^e(:) , [N,N,M] );

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by