3

I need some help with creating a data structure in Matlab. Until now I needed the following:

string1 value1
string2 value2
string3 value3

and so on. I used a structure for this:

mystruct = struct('mystrings', {}, 'myvalues', {});

Now additional to string and values I now need to assign several arrays (column vectors, containing only numbers) to my string-value pairs. It can be different, how many arrays are assigned to a string-value pair, e.g.

string1 value1 [1;2] [1;3]
string2 value2 [9;10]
string3 value3 [3;4] [2;9] [0;3]

I don't know how to create such a data structure. It's probably not a problem for me to get rid of a structure at all if it's the wrong data structure now. I need help on creating the new data structure, though. Thanks for any help :-)

1 Answer 1

6

There are always a lot of options when considering a "right" data structure. Some options:

  1. You could assign a cell array to each field of your structure.
    You would write to such a structure like this:

    data.field1{1} = 'a string';
    data.field1{2} = [1 2 3 4];
    data.field1{3} = [5:2:10];
    data.field2{1} = 'another string'
    

    and you would read it like this:

    allValueInACellArray = data.field1;
    onlyTheThirdValue = data.field1{3};
    
  2. You could use a nested structure.
    Then a write looks like this:

    data.field1.name = 'some name';
    data.field1.firstarray = [1 2 3 4];
    data.field1.secondarray = [5:2:10];
    data.field2.name = 'another name';
    

    and reads look like this:

    justTheFirstName = data.field1.name;
    onlyTheSecondArray = data.field1.firstArray;
    
  3. Another construct I use a lot is an array of structures.
    Combining this with a cell-valued field, a write looks like:

    data(1).name = 'some name';
    data(1).arrays = {[1 2 3 4]  5:2:10};
    data(2).name = 'another name';
    data(2).arrays = {[5 6 7 8]  6:3:12};
    

There is usually not a right answer to this. For small programs it doesn't really matter, you should just choose whatever feels most natural to you. For performance-limited applications you need to consider things like efficient memory allocation, and fast access to data in the manner which you usually need to access it.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice answer. Clearly MATLAB is not a language designed for creating expressive data structures.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.