Names of variables?

4 Ansichten (letzte 30 Tage)
Valeriy
Valeriy am 26 Okt. 2018
Kommentiert: Steven Lord am 26 Okt. 2018
Is it possible inside function to know the names of variables, which are used during call of this function? How to pass them inside it?
  2 Kommentare
Image Analyst
Image Analyst am 26 Okt. 2018
Yes, there is a way but it's so arcane that only Walter remembers it so you'll have to wait for him. You can get the names, as a cell array of strings, that were used in the main, calling routine when the function was called, which of course might be different than the names used in the function definition line. I have never needed to know this. Why do you want to know?
Valeriy
Valeriy am 26 Okt. 2018
Thanks, Image Analyst, for quick reply. Main idea is to use them inside figure captions, which are result of processing inside function. Of course, I can pass them as function parameters, but such way increase bulk of function call: I have to write names and them manually repeat them in text format. Cell array of names is convenient.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Steven Lord
Steven Lord am 26 Okt. 2018
IF those input arguments had names in the calling workspace of this function (which is not guaranteed) it is possible to retrieve those names using the inputname function.
However, I would be hesitant to use this information other than perhaps to use in an error message or text that you display as some sort of status. If you're thinking to use it with assignin to modify variables in your caller's workspace, I STRONGLY recommend against that unless there is no other way to do what you need (and even then, post about what you're trying to do on Answers to see if others can think of a better solution.) Doing that is likely to make debugging very difficult later on, and is an example of common coupling or perhaps even a form of content coupling. Prefer data coupling instead if possible.
  2 Kommentare
Valeriy
Valeriy am 26 Okt. 2018
Steven Lord, thanks a lot. inputname is function, which I'm looking for. And thanks for your warnings, I'm completely agree with you. My main idea of application of such function is something like:
title([... inputname(3) ...])
Steven Lord
Steven Lord am 26 Okt. 2018
I'd consider that as "some sort of status" message.
But you may need to do some preprocessing before your title call to handle the case where the input has no name. As the documentation states, inputname will return '' if the specified input is a literal constant like 5 or the result of an expression like x+1, sin(x), or x(42).

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Variables finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by