create variable from function input
6 views (last 30 days)
Show older comments
Hi, I was wondering if there's a way to create a variable that has the same name as one of the inputs you type in in a function? So for example:
if i have a function such as, function [output] = dosomething(input1, input2)
and when I call the function, I type in "data set1" for input 1 and "data set2" for input 2,
can I create a variable called "data set1" and "data set2" instead of input1, input2?
2 Comments
Richard Brown
on 11 Apr 2012
Short answer to your question: no (or certainly not as far as I'm aware -- I don't think you can access the text of the line that called the function from within the function)
But why would you want to do that?
If you want to access variables outside the scope of your function, you could either declare them global, or nest the function inside another one. But more often than not you won't actually need to do this. Maybe if you clarified what you're trying to do it would be easier to help ...
Stephen23
on 4 Jan 2015
Don't do this. The whole point of a function is that the workspace inside is independent of the calling workspace, and there should be no need to have any kind of variable name dependencies inside the function workspace.
Please explain why this is required, and we can probably show you a much better way to code this.
Answers (3)
Geoff
on 11 Apr 2012
This makes no sense. If you want your input variables to be called something else, then call them something else in the first place.
The point of function parameters is that you can refer to any supplied data using a single identifier. Just like algebra, if you don't mind a loose analogy
If you want to access dataset1 and dataset2 externally (without supplying them as inputs), then use the global keyword. Though I would not recommend it.
If there is something special about dataset1 and dataset2 then put them into a structure and encode their specific metadata in there.
I might be misinterpreting your question. At face-value, you have asked specifically if you can rename the variable input1 to data set1. The answer is no: you cannot have spaces in variable names. Use an underscore instead or join the words: ie data_set1 or dataset1.
I hope one of the above paragraphs helps. If not, you need to explain exactly what you are trying to achieve and why. =)
0 Comments
Walter Roberson
on 11 Apr 2012
If you want to know what the name of the variable passed in was, use inputname()
0 Comments
TAB
on 11 Apr 2012
It dosn't seem to be useful to create variables with the same name as input variables. But still you can do it as
function [output] = dosomething(input1, input2)
In1Name = inputname(1)
In2Name = inputname(2)
eval([In1Name '=0']); % Create variable
eval([In2Name '=0']); % Create variable
end
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!