Using cell array to define Argument list in function Handle
2 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(1 个)
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 个评论
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 Center 和 File Exchange 中查找有关 Multidimensional Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!