Using cell array to define Argument list in function Handle

조회 수: 3 (최근 30일)
Sandeep Parameshwara
Sandeep Parameshwara 2020년 1월 15일
편집: Matt J 2020년 1월 15일
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?

답변 (1개)

Matt J
Matt J 2020년 1월 15일
편집: Matt J 2020년 1월 15일
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
Sandeep Parameshwara
Sandeep Parameshwara 2020년 1월 15일
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 2020년 1월 15일
편집: Matt J 2020년 1월 15일
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] );

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by