creating a structure in for loop

9 views (last 30 days)
jinang patel
jinang patel on 22 Nov 2019
Edited: Stephen23 on 30 Apr 2020
Hello,
Is it possible to create a structure in a for loop
field={'name1','name2'}
for i=1:2
structure.(field{i})=value
end
Output:
structure.name1=value
structure.name2=value
Thanks
Jinang
  2 Comments
Ruger28
Ruger28 on 22 Nov 2019
Please, use the code format.
What are you having issues with? This will work just fine.
jinang patel
jinang patel on 22 Nov 2019
hey,
a={'see','why'}
KPI={'L','L2','L3'}
struc.a{1}.KPI{1}=5
Output
"struc =
struct with fields:
a: {[1×1 struct]}"
I would expect
struct.see.L=5

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 22 Nov 2019
Use the syntax shown in the MATLAB documentation:
>> a = {'see','why'};
>> KPI = {'L','L2','L3'};
>> S.(a{1}).(KPI{1}) = 5;
>> S.see.L
ans = 5
Read more:
  2 Comments
jinang patel
jinang patel on 29 Apr 2020
hello Stephen,
I am trying to assing value to each field name, however this is not possible since assign value to 1st field name limits the structure. Is there a way to assign value to individual fields?
a = {'see','why'};
KPI = {'L','L2','L3'};
S.(a{1})=6;
S.(a{1}).(KPI{1}) = 5;
Output
S.see=6;
S.see.L=5;
Stephen23
Stephen23 on 29 Apr 2020
Edited: Stephen23 on 30 Apr 2020
That is not possible. A field contains one array, i.e. the field can contain either a numeric array or another structure array, but it cannot simultaneously contain both.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!