1

I want to add elements in struct without looping like I have done below:

test_struct = struct ('item1', {} , 'item2' , {} ) ;
for k = 1 : 10
    test_struct(k).item1 = 1:10 ;
    test_struct(k).item2 = 2* (1:10) ;
end

Is there a way to add elements like adding elements in List in C#. I want a dynamic struct array because I do not know the how many elements, I will have to add in it.

2 Answers 2

1

Code

%%// First Data (normal arrays)
data1 = 1:10;
data2 = 2* (1:10);
test_struct1 = struct('item1', {data1}, 'item2', {data2});

%%// New Data (normal arrays) to be appended
data1 = 11:20;
data2 = 4* (1:15);

%%// Main step that appends new data
test_struct1(end+1) = struct('item1', {data1}, 'item2', {data2});

For verification, you may use this nice tool for comparing structures, as I don't think MATLAB has any built-in function for that, not in some of the previous versions of MATLAB at least.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. However I have still issues because I want to add normal arrays instead of cellarray.
@User1551892 Check out the edited code in Method 1. This might seal the deal for you!
I was looking something like you mentioned in Method1. Thanks a lot
0

You can do it in the struct statement itself:

A={1:10,1:10};
B={2*(1:10),2*(1:20)};
test_struct=struct('item1',A,'item2',B)

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.