Reputation: 4477
I am trying to initialize a structure in MATLAB similar to how C code does
typedef struct{
float x;
float y;
} Data
Data datapts[100];
From MATLAB, I know this is how to create a structure:
Data = struct('x', 0, 'y', 0)
but how do you create 100 instances of it?
Or is this not usually done in MATLAB? Does MATLAB prefer dynamic allocation whenever there is new data to add?
Upvotes: 5
Views: 12462
Reputation: 550
While each of the other answers are helpful, they don't actually address the question. If you would like to create a data structure that is only a blueprint until you instantiate it, you have to use a class.
Here's a class that will do the trick. Refer to the documentation for details on file structure.
classdef Data
properties
x = 0 % If you don't want to initialize upon instantiation,
y = 0 % you could instead have x/y {mustBeNumeric}
end
end
Then, instantiate it by calling dataPoint = Data
and use repmat to make 100 as you desire.
Upvotes: 1
Reputation: 42225
I don't know C, so I don't know how your code initializes the structure. However, consider these two possibilities:
data
with 100 elements, each of which has two fields x
and y
You can initialize an empty struct with
data = struct('x', cell(100,1), 'y', cell(100,1));
and you access each element of the struct array as data(1)
and each of these is a struct. Typically, these are used when you have several equivalent "things" with the same set of properties, but different values for each.
elements = struct(...
'name', {'Hydrogen', 'Helium', 'Lithium'},...
'atomicWeight', {1, 4, 7}, ...
'symbol', {'H', 'He', 'Li'});
elements(1)
ans =
name: 'Hydrogen'
atomicWeight: 1
symbol: 'H'
So you can access each individual struct to get to its properties. Now if you wanted to append a struct array with the next 10 elements to this list, you can use cat
, just like you would for matrices.
data
with two fields x
and y
, each with 100 elementsYou can initialize this as
data = struct('x',zeros(100,1),'y',zeros(100,1));
and you access each element of the field as data.x(1)
. This is typically used when you have one "thing" with several properties that can possibly hold different values.
weather=struct('time',{{'6:00','12:00','18:00','24:00'}},...
'temperature',[23,28,25,21]);
Once you understand structs and struct arrays and how they're used and indexed, you can use them in more complicated ways than in the simple illustration above.
Upvotes: 14
Reputation: 5251
In addition to the other methods described by @yoda and @Jacob, you can use cell2struct
.
Upvotes: 1
Reputation: 34601
repmat(Data,100,1);
You can assign data to it with:
Data(1).x = 10;
Data(1).y = 20;
Upvotes: 5