How to get exact function's argument names?

2 visualizaciones (últimos 30 días)
grega
grega el 29 de Nov. de 2017
Respondida: Aashray el 25 de Feb. de 2025
I created own function myfunc(d.A,d.B) where A and B are vectors in structure d. In the function I'd like to get exact myfunc's argument names, i.e. 'd.A d.B' or 'd.A', 'd.B'. Matlab's builtin inputname function throws '0×0 empty char array'. Any suggestions please?

Respuestas (1)

Aashray
Aashray el 25 de Feb. de 2025
Hello Grega!
According to MathWorks documentation, “inputname()” in MATLAB cannot retrieve argument names when they are passed using forward indexing (e.g., “d.A” or “d.B”). It only works when you pass the actual variable names, not the values from structure fields. This happens because “inputname()” tracks the variable name as it appears in the calling workspace, but when you access structure fields (like “d.A”), it only passes the values, not the original field names.
One workaround is to pass the structure itself and access the field names within the function manually. Here’s an example of how you can modify your code:
d.A = 15;
d.B = 54;
result = myFunc(d, 'A', 'B'); % Pass structure and field names explicitly
Field 1: d.A Field 2: d.B
function temp = myFunc(d, fieldA, fieldB)
disp(['Field 1: ', inputname(1), '.', fieldA])
disp(['Field 2: ', inputname(1), '.', fieldB])
temp = d.(fieldA) + d.(fieldB); % Access fields dynamically using field names
end
  • Instead of passing “d.A” and “d.B” as arguments, we now pass the structure d along with the field names 'A' and 'B' as string arguments.
  • Inside the function, we display the field names and use dynamic field access with d.(fieldName) to compute the sum.
This way, you can retrieve and display the field names explicitly, and the function will work as expected, hope you find it useful!
Attaching documentation link for reference: https://www.mathworks.com/help/matlab/ref/inputname.html

Categorías

Más información sobre Argument Definitions en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by