Select Structure Field Based on Variable

조회 수: 30 (최근 30일)
Louis-Thomas Roy
Louis-Thomas Roy 2022년 9월 19일
댓글: Stephen23 2022년 9월 19일
Let's say I have a structure with multiple fields structured like this:
Structure.A = 5;
Structure.B = 10;
Structure.C = 30;
If I have a variable:
Field = "B"
Can I select the field B in the structure and set it equal to a new value? When I run this code, it creates a new field called "Field" instead of selecting the existing one from the value of Field.
Structure.Field = 15;

채택된 답변

Bhaskar R
Bhaskar R 2022년 9월 19일
There is special notation to access structure or class field using parenthesis () of input string
Structure.A = 5;
Structure.B = 10;
Structure.C = 30;
Field = "B"
Field = "B"
Structure.(Field) = 15 % this updates required field without adding extra field
Structure = struct with fields:
A: 5 B: 15 C: 30

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by