I have three vectors centers, radiuses, metrics
all Nx1 (centers
is Nx2, but it is not a problem at all). And I want to convert them into vector Nx1 of structures where each structure has fields: center, radius, metric
and corresponding values of this fields, like structArray(i).metric == metrics(i)
. What is the best and simpliest way to do this?
Asked
Active
Viewed 245 times
1
2 Answers
2
You can use the struct
constructor directly by converting you data to cell arrays.
structArray = struct('center', num2cell(centers,2), ...
'radius', num2cell(radiuses), ...
'metric', num2cell(metrics));
Note the use of the dimension input to num2cell
to convert the centers
variable into an Nx1 array of 1x2 cells.
If we try this with some example data:
radiuses = rand(3,1);
metrics = rand(3,1);
centers = rand(3,2);
structArray = struct('center', num2cell(centers,2), ...
'radius', num2cell(radiuses), ...
'metric', num2cell(metrics));
structArray =
3x1 struct array with fields:
center
radius
metric

Suever
- 64,497
- 14
- 82
- 101
1
Use the following:
S = struct( 'centers', num2cell(centers), 'radiuses', num2cell(radiuses), ...
'metrics', num2cell(metrics) );
Note, that the overhead (in terms of memory consumption) of this approach is very high. If your arrays CENTERS, RADIUSES and METRICS are very large it is better to use the "flat" memory layout, i.e. to store the arrays in one struct:
S = struct;
S.centers = centers;
S.radiuses = radiuses;
S.metrics == metrics;

Andreas H.
- 5,557
- 23
- 32