Construct a new structure r' from a first one r by adding new elements.
Info
This question is closed. Reopen it to edit or answer.
Show older comments
Hy,
I have a code which gives a structure r (like shown below) and I want to add values D_1 to D_6 "given as data" to construct a new structure r' shown also below as an example.
Can you tell me how to do this please?
r =
struct with fields:
D_1_2: 1.9202e+03
D_1_3: 3.4417e+03
D_1_4: 1.9331e+03
D_1_5: 1.8763e+03
D_1_6: 1.1525e+03
D_2_3: 3.4421e+03
D_2_4: 1.9335e+03
D_2_5: 1.8986e+03
D_2_6: 1.2044e+03
D_3_4: 3.4898e+03
D_3_5: 101.9928
D_3_6: 3.4193e+03
D_4_5: 1.8928e+03
D_4_6: 1.1630e+03
D_5_6: 1.1600e+03
r' =
struct with fields:
D_1: valeur
D_2: valeur
D_3: valeur
D_4:valeur
D_5:valeur
D_6:valeur
D_1_2: 1.9202e+03
D_1_3: 3.4417e+03
D_1_4: 1.9331e+03
D_1_5: 1.8763e+03
D_1_6: 1.1525e+03
D_2_3: 3.4421e+03
D_2_4: 1.9335e+03
D_2_5: 1.8986e+03
D_2_6: 1.2044e+03
D_3_4: 3.4898e+03
D_3_5: 101.9928
D_3_6: 3.4193e+03
D_4_5: 1.8928e+03
D_4_6: 1.1630e+03
D_5_6: 1.1600e+03
Answers (1)
Steven Lord
on 1 Mar 2017
rprime = r;
rprime.D_1 = 42;
% etc.
If you had a cell array containing the names of the fields you want to add to rprime along with a data array of the same size, use dynamic field names.
fieldsToAdd = {'apple', 'banana', 'coconut'};
dataToAdd = [5, 6, 7];
for k = 1:length(fieldsToAdd)
thefield = fieldsToAdd{k};
thedata = dataToAdd(k);
rprime.(thefield) = thedata;
end
Note I used curly braces to retrieve the field name but parentheses to retrieve the field data, since the data was stored in a numeric vector. If your data was a different size for each field, you would also need to store it in a cell array and use curly brace indexing to extract it from the cell.
This question is closed.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!