Instead of changing the value, it is simpler to rebuild the structure array.
Get value by IndexingArray
:
val = Values(IndexingArray+1);
Build array of structures using cell2struct
, and convert to cell array using num2cell
:
T = num2cell(cell2struct(val, {'C'}, 1));
Convert T
result to array of structures using cell2struct
:
A = cell2struct(T', {'B'}, 1);
Here is the code sample to create A:
Values = {'a', 'b'};
IndexingArray = [1 1 0 1];
val = Values(IndexingArray+1);
T = num2cell(cell2struct(val, {'C'}, 1));
A = cell2struct(T', {'B'}, 1);
Building A in a single line of code:
A = cell2struct((num2cell(cell2struct(Values(IndexingArray+1), {'C'}, 1)))', {'B'}, 1);
Result (for testing):
>> A(1).B.C
ans =
b
>> A(2).B.C
ans =
b
>> A(3).B.C
ans =
a
>> A(4).B.C
ans =
b
Solution using arrayfun
:
val = Values(IndexingArray+1);
A = arrayfun(@(x) struct('B', struct('C', val{x})), 1:4)
Update specific elements of A:
In case you need to update specific elements, instead overwriting A
, you can apply arrayfun
selectively, to the indexes, you know you need to update.
Example:
Assume A
length is 6 elements, and you need to update the first 4, you can use the following code:
A(1:4) = arrayfun(@(x) struct('B', struct('C', val{x})), 1:4);
Assume you know you need to update only A(1)
and A(4)
, you can use the following example:
A(1).B.C = 'a';
A(2).B.C = 'b';
A(3).B.C = 'a';
A(4).B.C = 'a';
A(5).B.C = 'c';
A(6).B.C = 'd';
Values = {'a', 'b'};
IndexingArray = [1 1 0 1];
val = Values(IndexingArray+1);
%List of indices of A to update
indices = [1, 4];
A(indices) = arrayfun(@(x) struct('B', struct('C', val{x})), indices);