Using cell array to define Argument list in function Handle

4 visualizzazioni (ultimi 30 giorni)
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{h}=rho{h}.Name;
end
>> 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?

Risposte (1)

Matt J
Matt J il 15 Gen 2020
Modificato: Matt J il 15 Gen 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.';
where
Qvector=[Q0,Q1,...,Q50]
rhoVector=[rho0,rho1,...,rho50]
You should also be using vectorized commands to create these vectors. You should not be creating Q0,Q1, etc... one element at a time.
  2 Commenti
Sandeep Parameshwara
Sandeep Parameshwara il 15 Gen 2020
Hi Matt,thank you I will try this. In my question, Q's are all symmetric matrices and rho's are all scalar. And I also might have non uniform pattern in my function, something like this
Q=@(rho1,rho2) Q0 + Q1*(rho1)^2 +Q2*(rho2);
Matt J
Matt J il 15 Gen 2020
Modificato: Matt J il 15 Gen 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
[N,~,M]=size(Qarray);
Q =@(rho) reshape( reshape(Qarray,[],M)*rho(:).^e(:) , [N,N,M] );

Accedi per commentare.

Prodotti


Release

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by