0

I have a structure variable and want to add a field and fill the row with the values of an array (double). The following code works but isn't very nice. Is there a more elegant way to add a field including values without the use of the mat2cell function or a for loop?

field1 = 1:10
field2 = 4:13
%create struct with field 'start' with 10 values
A = struct('start',mat2cell(field1,1,ones(1,numel(field1))))
%transform field2 to cell 
temp = mat2cell(field2,1,ones([numel(field2),1]));
%add field 'end' with 10 values
[A(1:numel(field2)).end] = temp{:};

2 Answers 2

2

You can use num2cell rather than mat2cell which will (by default) place each element in it's own cell. Unfortunately, you will still need a temporary variable.

A = struct('start', num2cell(field1));
tmp = num2cell(field2);
[A.end] = tmp{:};
Sign up to request clarification or add additional context in comments.

Comments

1

Download "catstruct": https://www.mathworks.com/matlabcentral/fileexchange/7842-catstruct

clear
field1 = 1:10;
field2 = 4:13;
A = struct('start',num2cell(field1));
A = catstruct(A, struct('end',num2cell(field2)));

For performance you better use single field that contain array:

clear
field1 = 1:10;
field2 = 4:13;
A=[];
A.start = field1;
A.end = field2;

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.