Matlab array of structure

45 views Asked by At

I created an array of structures

data(1).field = 5;
data(2).field = 3;
data(3).field = -4;
...

I would like to plot one of the fields by accessing something like:

data(:).field

I get the following error:

Expected one output from a curly brace or dot indexing expression, but there were 1000 results.

Is it possible to get the data without using a loop?

2

There are 2 answers

0
John Bofarull Guix On

try getfield

like this

getfield(S(:),field)

getfield reads nested fields, as in

S.f1.f2.f3

then the call is

getfield(S,f1,f2,f3)

complete MATLAB help file here:

https://uk.mathworks.com/help/matlab/ref/getfield.html

0
cui xingxing On

Is it possible to get the data without using a loop?

Yes,there are several ways to avoid for loops to get data.

In order to avoid the for loop(which that can only be a level by level), this can be done through the square brackets "[]" or convert matlab struct arrays to other matlab built-in data types (such as table, cell, etc.), the general use of the function is struct2table, struct2cell.


  • use "[]"

Actually converts the comma expression to a scalar array. For a tutorial on how to use comma expressions see the discussion at the following link.

https://www.mathworks.com/matlabcentral/discussions/tips/847976-tutorial-comma-separated-lists-and-how-to-use-them

  • convert to other build-in data type

This actually converts the struct array into another data representation presentation, with the sub-field(sub-level, which is usually the result returned by the fieldnames function) still being a scalar struct.


When you know the fieldname of a level beforehand, you can get the data of the next level in any of the above two ways.

For example:

data(1).level1_a.level2_a = 5;
data(2).level1_a.level2_a = 3;
data(3).level1_a.level2_a = -4;
data(4).level1_a.level2_a = 8;

data(1).level1_b.level2_b = 2;
data(2).level1_b.level2_b = 3;
data(3).level1_b.level2_b = 7;
data(4).level1_b.level2_b = 10;

% get struct data, avoid for loops
level1Names = fieldnames(data)
level2Names = fieldnames(data(1).(level1Names{1}))
tbl = struct2table(data) % The column name is the name of level1.

value1 = [tbl.level1_a.level2_a] % get the data
value2 = [tbl.level1_b.level2_b] % get the data

cel = struct2cell(data) % 2*1*4 cell array