开发者

Assignin in second level struct

开发者 https://www.devze.com 2023-02-16 23:12 出处:网络
I am dealing with a small tricky issue in matlab: I want to assign values to a dynamically created struct (2. level):

I am dealing with a small tricky issue in matlab:

I want to assign values to a dynamically created struct (2. level):

my struct looks like this:

a.b.c = 1    %Creates a struct with two levels

now I want to autofill a.b with c1, c2, c3,...cn as neighbor-elements to c. Also the firste leven b must be开发者_如何学编程 changed dynamically, so I can not hardcode any 'path'...All values consist of a prefix (e.g. b or c) and a postfix (just a number increased by a loop)

My main concern is, that this process MUST be done by a loop and not by hand (otherwise I would do many copy/paste lines with manual edits).

It would be great if someone could give me a hint.

greets, poeschlorn


I'm not exactly sure if this is what you're looking for. It uses dynamic field names to create eleven b entries and n c entries:

>> n = 5;
>> for ii = 1:11
for jj = 1:n
a.b(ii).(sprintf('c%u', jj)) = 1;
end
end
>> a

a = 

    b: [1x11 struct]

>> a.b(1)

ans = 

    c1: 1
    c2: 1
    c3: 1
    c4: 1
    c5: 1

>> a.b(3)

ans = 

    c1: 1
    c2: 1
    c3: 1
    c4: 1
    c5: 1


b3's solution shows you how to create the fields with a loop, but please "don't do that". Can't you use a cell array? E.g.

a.b.c = cell( 1, n );
for ii=1:n
  a.b.c{ii} = rand(ii);
end
0

精彩评论

暂无评论...
验证码 换一张
取 消