Fast way of concatenating complex data using vertcat with custom rows

I need to concatenate few bigger matrices, but in specific manner - for example to concatenate only 1 row from X matrices. There is a good solution of storing the data in a structure, so then there is no need of preparing long list of things that needs to be concatenated.

For example, we will have a structure like that:

struct(1).huge = [1 2 3 4; 1 2 3 4]; struct(2).huge = [1 2 3 4; 1 2 3 4]; struct(3).huge = [1 2 3 4; 1 2 3 4]; 

Then we can concatenate these with:

concatVar.concat = vertcat(struct.huge); 

Instead of, for example:

concatVar.concat = vertcat(struct(1), struct(2),(...),struct(100)); 

But what if I need to concatenate only specific rows from different fields in the structure, for example only 1 row:

concatVar.concat = vertcat(struct.huge(1,:)); 

Then this method will not work, with the error:

"Expected one output from a curly brace or dot indexing expression, but there were X results".

Is it even possible of doing something like that in a fast and reliable way with use of vertcat or horzcat?

Thanks for any advice! BM

1

1 Answer

It seems hard to avoid a loop in this case. You can convert the struct's field into a cell and then use cellfun, which is essentially a loop.

Let your struct be defined as follows. Note that it's not advised to use function names or reserved words like struct as variable names.

s(1).huge = [1 2 3 4; 1 2 3 4]; s(2).huge = [1 2 3 4; 1 2 3 4]; s(3).huge = [1 2 3 4; 1 2 3 4]; 

Then:

result = cell2mat(cellfun(@(x) x(1,:), {s.huge}, 'uniformoutput', false).'); 
0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like