- 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.
How to get exact function's argument names?
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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?
0 Commenti
Risposte (1)
Aashray
il 25 Feb 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
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
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
0 Commenti
Vedere anche
Categorie
Scopri di più su Argument Definitions in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!