1

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
    "There is a good solution of storing the data in a structure" As you can see in the answer below, an even better solution is using a cell array. If there is only one thing in each element of the array (as in this case, struct(ii).huge), you don't need that huge name there. Commented Apr 5, 2019 at 14:29

1 Answer 1

3

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

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.