Is it possible to extract all fields from a structure automatically?

조회 수: 256 (최근 30일)
Mr M.
Mr M. 2016년 8월 10일
편집: Vibin Jacob 2024년 11월 15일 11:03
I have data in the form: mydata.x = 100; mydata.s = 'abc'; mydata.Y = [1 2 3]; And I want variables x = 100; s = 'abc'; Y = [1 2 3]; How to extract variables automatically? (suppose that I don't know the names of the variables!)
  댓글 수: 7
Mr M.
Mr M. 2016년 8월 10일
Why anybody think that this is a dynamic variable in my example? I think this is simple loading problem and not dynamic variable.
Stephen23
Stephen23 2019년 11월 14일
편집: Stephen23 2019년 11월 14일

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

채택된 답변

Stephen23
Stephen23 2016년 8월 11일
편집: Stephen23 2016년 8월 11일
You seem intent on magically making variables pop into existence in the workspace, so here is probably the least-worst way of doing that. The trick is to change the save command by adding the '-struct' option:
>> S.name = 'anna';
>> S.data = 1:3;
>> save('temp.mat','-struct','S')
and then load it like this:
>> clear
>> load('temp.mat')
>> name
name = anna
>> data
data =
1 2 3
and you will find all of those variables in your workspace.

추가 답변 (3개)

Baium
Baium 2019년 11월 14일
편집: Baium 2019년 11월 14일
Alternative, maybe this is more desired than dictating how the struct will be saved in the workspace (this will recursively unpack any struct within the struct):
function unpackStruct (structure)
fn = fieldnames(structure);
for i = 1:numel(fn)
fni = string(fn(i));
field = structure.(fni);
if (isstruct(field))
unpackStruct(field);
continue;
end
assignin('base', fni, field);
end
end
  댓글 수: 6
Alec Jacobson
Alec Jacobson 2021년 5월 9일
Or as a single anonymous function (which you can drop into your ide)
unpackStruct = @(s) cellfun(@(name) assignin('base',name,getfield(s,name)),fieldnames(s));

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


Azzi Abdelmalek
Azzi Abdelmalek 2016년 8월 10일
편집: Azzi Abdelmalek 2016년 8월 10일
Use fieldnames function
mydata.x = 100;
mydata.s = 'abc';
mydata.Y = [1 2 3];
field=fieldnames(mydata)
Then you want to assign to each variable individually a corresponding value, which is not recommended. Read this http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F

Vibin Jacob
Vibin Jacob 2024년 11월 15일 11:02
편집: Vibin Jacob 2024년 11월 15일 11:03
who / whos function when called without any argument, lists all the variables in the current workspace with their properties.

카테고리

Help CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by