Structure fields to variables

버전 1.1.0.1 (2.09 KB) 작성자: Matt J
Code writing tool for importing/exporting workspace variables to or from a struct.
다운로드 수: 4.3K
업데이트 날짜: 2019/7/29

라이선스 보기

Structures are a convenient way of carrying around many variables as a single object and of passing those variables to a function packed in a single argument.
Once a structure has been passed to a function, however, many users (according to various Newsgroup posts) find it tiresome to have to access its fields repeatedly through dot-indexing notation and have sought automated ways to take a structure and assign all of its fields to separate variables, as in
a = myStruct.a;
b = myStruct.b;
c = myStruct.c;
etc...
Solutions based on assignin() have often been tried, but are hazardous, for reasons discussed, for example, in this thread:

http://www.mathworks.com/matlabcentral/newsreader/view_thread/244639#628695

The structvars() tool in this FEX submission does something virtually as good and far safer.

Given a structure, it will print the lines of code needed to assign structure fields to separate variables (or the reverse). The lines of code can be conveniently copy/pasted from the command window to the file editor at the location in the file where the variables need to be unpacked.


Examples: Given structure myStruct, with fields a,b,c, & d

(1) structvars(myStruct) %assign fields to variables

ans =

a = myStruct.a;
b = myStruct.b;
c = myStruct.c;
d = myStruct.d;

(2) structvars(3,myStruct) %split the last result across 3 columns

ans =

a = myStruct.a; c = myStruct.c; d = myStruct.d;
b = myStruct.b;

(3) structvars(3,myStruct,0) %assign variables to fields

ans =

myStruct.a = a; myStruct.c = c; myStruct.d = d;
myStruct.b = b;

The commands can obviously be regenerated if you add/remove structure fields later on. On the other hand, the effort of just making these incremental edits manually is typically minimal.

인용 양식

Matt J (2024). Structure fields to variables (https://www.mathworks.com/matlabcentral/fileexchange/26216-structure-fields-to-variables), MATLAB Central File Exchange. 검색 날짜: .

MATLAB 릴리스 호환 정보
개발 환경: R2009b
모든 릴리스와 호환
플랫폼 호환성
Windows macOS Linux
카테고리
Help CenterMATLAB Answers에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!
버전 게시됨 릴리스 정보
1.1.0.1

Description update

1.1.0.0

When called with no output arguments, structvars now simply prints the assignment statements to the screen. This is for compatibility with new display conventions in R2017.
Edit title

1.0.0.0