0

I am trying to add a datapoint to an existing data struct. I have created the following data struct.

ourdata.animal= {'wolf', 'dog', 'cat'}
ourdata.height = [110 51 32]
ourdata.weight = [55 22 10]

say I want to add another one to the data struct with name 'fish' height 3 and weight 1, how do I go about this?

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Coderman
  • 159
  • 9

2 Answers2

2

You can simply attach it to the end of the structure:

ourdata.animal{end+1} = 'fish'
ourdata.height(end+1) = 3
ourdata.weight(end+1) = 1
Adriaan
  • 17,741
  • 7
  • 42
  • 75
0

If you want to work with multiple structures, you can write a little function to combine the values of fields in multiple structs. Here's one, using fieldnames() to discover what fields exist:

function out = slapItOn(aStruct, anotherStruct)
% Slap more data on to the end of fields of a struct
out = aStruct;
for fld = string(fieldnames(aStruct))'
    out.(fld) = [aStruct.(fld) anotherStruct.(fld)];
end
end

Works like this:

>> ourdata
ourdata = 
  struct with fields:

    animal: {'wolf'  'dog'  'cat'}
    height: [110 51 32]
    weight: [55 22 10]
>> newdata = slapItOn(ourdata, struct('animal',{{'bobcat'}}, 'height',420, 'weight',69))
newdata = 
  struct with fields:

    animal: {'wolf'  'dog'  'cat'  'bobcat'}
    height: [110 51 32 420]
    weight: [55 22 10 69]
>> 

BTW, I'd suggest that you use string arrays instead of cellstrs for storing your string data. They're better in pretty much every way (except performance). Get them with double quotes:

>> strs = ["wolf" "dog" "cat"]
strs = 
  1×3 string array
    "wolf"    "dog"    "cat"
>> 

Also, consider using a table array instead of a struct array for tabular-looking data like this. Tables are nice!

>> animal = ["wolf" "dog" "cat"]';
>> height = [110 51 32]';
>> weight = [55 22 10]';
>> t = table(animal, height, weight)
t =
  3×3 table
    animal    height    weight
    ______    ______    ______
    "wolf"     110        55  
    "dog"       51        22  
    "cat"       32        10  
>> 
Andrew Janke
  • 23,508
  • 5
  • 56
  • 85