필터 지우기
필터 지우기

Is there the more elegant way to do this?

조회 수: 2 (최근 30일)
G A
G A 2014년 1월 28일
편집: G A 2014년 1월 31일
I would like to call arguments of function from a string or cell array. For example, this code works as I want:
function testarg()
a=1;b=2;c=3;
m='a,b,c';
eval(['myfun(',m,')']);
function myfun(a,b,c)
a
b
c
Is there another way to do this? Say, without using eval ?
  댓글 수: 2
Jos (10584)
Jos (10584) 2014년 1월 29일
Just a tip: whenever you found yourself using eval, you will be 99.999% sure that there is a way to do it some other way without using eval that is:
  • more efficient
  • less error-prone
  • without hideous side-effects
  • easy to code, read and maintain
  • ...
eval(char('chro''&HB@MCNVHSGNTSDU@K &('+1))
G A
G A 2014년 1월 29일
편집: G A 2014년 1월 29일
Thanks, Jos. I knew how 'bad' is eval- this matter was intensively discussed here by the community. I just wanted to demonstrate my purpose - it was my desperate try to achieve what I want.:)

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

채택된 답변

Matt J
Matt J 2014년 1월 28일
function myfun(varargin)
varargin{:}
  댓글 수: 17
Matt J
Matt J 2014년 1월 31일
편집: Matt J 2014년 1월 31일
It sounds like you should be assigning your data to struct fields, rather than to individual variables.
S.a=1;
S.b=2;
S.c=3;
Now everything is conveniently bundled in S and you can pass that around to functions as a single argument.
G A
G A 2014년 1월 31일
편집: G A 2014년 1월 31일
Thanks, Matt! Now I can rename all my variables myname to S.myname and use them as before within my program and pass to functions as single argument S. Previous solution - to use variables as C{1}, C{2} is not convenient - without names. Originally, I thought there could be a way to pass the names as 'a', 'b', which I could bundle as C={'a','b'}...

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

추가 답변 (1개)

Amit
Amit 2014년 1월 28일
function testarg()
a=1;b=2;c=3;
abc(a,b,c)
function abc(a,b,c)
a
b
c
This wil ldo just fine.
  댓글 수: 4
Amit
Amit 2014년 1월 28일
See MAtt's solution. That will do it.
G A
G A 2014년 1월 28일
Thank you, Amit!

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

카테고리

Help CenterFile Exchange에서 Scope Variables and Generate Names에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by