Create a new structure using a function in a for loop.

조회 수: 4 (최근 30일)
Allen Hammack
Allen Hammack 2022년 5월 11일
편집: Stephen23 2022년 5월 12일
I have a structure, and I want to use the values of one of the fields as the names of new structures. So, for instance, I have structure "struct" with the field "field" that has the following values that are strings:
'value1'
'value2'
'value3'
I have a function whose output is a new structure that I want to be the name of the field values in my first structure (so, value1, value2, and value3) and whose input I also want to be the name of the field values in my first structure. I'm trying to create the new structures (named value1, value2, and value 3 using a for loop like this
for j = 1 length(struct.field)
[struct.field{j}] = function(struc.field{j})
end
The error I'm getting is
Dot indexing is not supported for variables of this type.
Other than the for loop portion, my function works as long as I manually specify the new structure name. I'm trying to avoid manually specifying the new structure name if possible.
Can I create new structures using a function in a for loop like what I've been trying? If so, what do I need to do to fix my method?
Thanks!
  댓글 수: 5
Allen Hammack
Allen Hammack 2022년 5월 12일
@Stephen23 Thank you for the links!
The first link explains why to not dynamically name variables. I will look into that further.
The second link shows how to generate field names from variables. Is the second link the preferred approach or just about showing how to dynamically name variables, which is bad practice?
Thanks!
Stephen23
Stephen23 2022년 5월 12일
편집: Stephen23 2022년 5월 12일
"The second link shows how to generate field names from variables."
Correct.
"Is the second link the preferred approach..."
"preferred": maybe. Dynamic fieldnames might be quite a suitable approach... or perhaps not. Or perhaps a table... Or a cell array... Or an ND array. It depends very much on your data (e.g. sizes, types, how they are structured, etc), what processing you will do on them, etc.
In general fieldnames (just like variable names) should not contain meta-data (your 'value1', 'value2', etc. are probably meta-data). Meta-data should be stored in a variable, not in its name. Perhaps a structure array might be a good choice for storing that data:
S(1).data = [..];
S(1).name = 'value1';
S(2).data = [..];
S(2).name = 'value2';
..
"or just about showing how to dynamically name variables, which is bad practice?"
Generating fieldnames from variables has nothing (directly) to do with dynamic variable names. Fields are not variables.

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

답변 (0개)

카테고리

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

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by