- 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 (최근 30일)
이전 댓글 표시
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
답변 (1개)
Aashray
2025년 2월 25일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Argument Definitions에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!