Unpack structure, only some fields
이전 댓글 표시
Suppose I have the structure par with fields
par.a=3.5;
par.b=[4;1.2];
par.c='ale';
I want to create variables b and c such that b=par.b and c=par.c. To do this, I wrote a simple function and I type
clear
par.a=3.5;
par.b=[4;1.2];
par.c='ale';
[b,c] = unpack(par,{'b','c'}); %too long, I don't wanna pass {'b','c'}
disp(b)
disp(c)
function varargout = unpack(par,varnames)
nvar = numel(varnames);
varargout = cell(nvar,1);
for i=1:nvar
varargout{i} = par.(varnames{i});
end
end
This does what I want. However I would like to type simply
%[b,c] = unpack(par);
and NOT
%[b,c] = unpack(par,{'b','c'});
Is it possible to modify my function so that I don't have to give the names of the fields that I want to extract as a second input? When you have to unpack many variables it can be tedious.
Any help would be greatly appreciated!
댓글 수: 1
Steven Lord
2023년 2월 27일
Can you dynamically create variables from a struct array with names generated from the names of the fields? Yes.
Should you do this? The general consensus is no. That Answers post explains why this is generally discouraged and offers several alternative approaches.
For example, suppose your struct array had a field named exit. If you ran your code in a function file then tried to access that variable, well, don't try it if you have any unsaved variables in your workspace that you want to keep.
If you believe you have a use case where you need to do this that's not covered in the Answers post I linked above, please explain what you're hoping to do with those dynamically created variables.
채택된 답변
추가 답변 (1개)
make use of fieldnames()?
Avoid using the unpack() name. There is a built-in function with the same name.
par.a=3.5;
par.b=[4;1.2];
par.c='ale';
fieldnames(par)
카테고리
도움말 센터 및 File Exchange에서 Data Type Identification에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!