1

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?

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

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.