1

I have a function that returns arrays of struct arrays. I want to call this function repeatedly, appending the returned value to another array, but I'd like to append the returned value as a single element of the larger array. cat() doesn't seem to work for me because it appends every element of the returned value individually to the larger array.

In the context of the following example, how do I add foo to bar as a single element of bar?

foo(1).id = 1;
foo(1).v = 'a';
foo(2).id = 2;
foo(2).v = 'b';

bar = [];
bar = cat(1, bar, foo); % Adds each element of foo individually

1 Answer 1

3

If I am interpreting your question correctly, you would like each element in this "array" to be this array of structures that's returned by the function. What you are doing in your code below is simply creating a larger structure array and appending each of the elements in the structure array to this larger structure array.

You probably want to use cell arrays instead. Simply put, change bar = []; to bar = {};. When you're done, you can access each element by using curly braces (i.e. {}) and the index of where you want to access:

% Your example data
foo(1).id = 1;
foo(1).v = 'a';
foo(2).id = 2;
foo(2).v = 'b';

% Add another one for proof of concept
foo2(1).id = 3;
foo2(1).v = 'c';
foo2(2).id = 4;
foo2(2).v = 'd';

bar = {}; % Change
bar = cat(1, bar, foo);
bar = cat(1, bar, foo2); % Add another nested structure array in

baz = bar{1}; % Get the first nested structure array
baz2 = bar{2}; % Get the second nested structure array
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, for anyone coming from anther language where arrays are indexed by objects (arrays within arrays are interpreted as single objects rather than a matrix "row", or whatever), the cell array is your savior.
@jphollowed Thanks :) An upvote wouldn't come amiss :D... optional of course.
@jphollowed lol that was quick. Thank you. BTW if it sounded like I was begging, please ignore. You have the right to do whatever you want.

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.