how to use a parameter name list as input for a function?

Dear All,
I have a tryparel function as below
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function out=tryparel(paramlist)
disp(a)
disp(b)
out=a+b;
%%%%%%%%%%%%%%%%%%%%%%%%%%%
To use this function above I would like to do below
paramlist=['a,' , 'b'];
out=tryparel(paramlist)
BUT I always get errors. Can anyone help me about this?
I have to write a script calling this type of function where the input variable list is really long.
Thanks

Réponses (1)

Sven
Sven le 3 Avr 2013
Modifié(e) : Sven le 4 Avr 2013
Skirt, you were very close. You just need to use a cell array:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function out=tryparel(paramlist)
disp(a)
disp(b)
out=a+b;
%%%%%%%%%%%%%%%%%%%%%%%%%%%
paramlist = {4 , 10};
out = tryparel(paramlist{:})
If you instead want to do something like this:
a = 4;
b = 10;
paramlist = {'a','b'};
... then don't do this. Instead use a structure such as:
P.a = 4;
P.b = 10;
paramNameList = {'a','b'};
paramList = cellfun(@(name)P.(name), paramNameList, 'Un',0)
out = tryparel(paramList{:})
Did this answer your question? If so, be sure to hit "accept".

3 commentaires

Hi Sven,
Thanks a lot for your help. However when I execute the code P.a = 4; P.b = 10; paramNameList = {'a','b'}; paramList = cellfun(@(name)P.(name), paramNameList, 'Un',0) out = tryparel(paramlist{:})
it shows error message ??? Undefined variable "paramlist" or class "paramlist".
%%%%%%%my function is written as below out = tryparel(paramlist ) function out=tryparel(paramlist )
disp(a)
disp(b)
out=a+b;
Do you know what can be wrong here?
Thanks
Sven
Sven le 4 Avr 2013
Modifié(e) : Sven le 4 Avr 2013
Oh, small typo. Use:
out = tryparel(paramList{:})
instead of:
out = tryparel(paramlist{:})
In my last example I used some capital letters to help distinguish between paramNameList (which is just the set of variable names to use) and paramList which is the actual variables.
thanks a lot

Connectez-vous pour commenter.

Catégories

En savoir plus sur Mathematics dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by