How do I access a field from a function's input?

조회 수: 21 (최근 30일)
Andy Garcia Barrabeitg
Andy Garcia Barrabeitg 2022년 1월 10일
댓글: Andy Garcia Barrabeitg 2022년 1월 10일
Hello, I currently have a struct with different field names "Delta", "Theta", "Beta", and "Gamma". I'd like to be able to call upon these different fields in my function based on some input "freq" (sample code below). However, whenever I try to access the field from the variable it takes the variable as a literal value "freq" instead of the input in the function and thus I get an error that it can't find myStruct.freq. Is there a way I could go around this? Thanks!
function[output] = myFunction(freq)
output = myStruct.freq
end

채택된 답변

James Tursa
James Tursa 2022년 1월 10일
편집: James Tursa 2022년 1월 10일
Assuming you are passing in a character string for freq, use this syntax:
output = myStruct.(freq);
  댓글 수: 3
James Tursa
James Tursa 2022년 1월 10일
You need to pass in the myStruct variable to the function also. But, quite frankly, if that is all the function does in your actual case I wouldn't even bother with the function at all. Just use the appropriate syntax in your calling code and avoid the function all together.
Andy Garcia Barrabeitg
Andy Garcia Barrabeitg 2022년 1월 10일
Ah okay, thank you James!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by