bgoosman
bgoosman

Reputation: 717

How can I flatten every n rows in matrix using Matlab?

I can easily flatten an entire matrix into one row using reshape(M,1,[]). However, this time I want to flatten every n rows into one row. Thus, if we start with 100 rows and n=10, we will end up with 10 rows.

e.g.

1 2 3
4 5 6
7 8 9
10 11 12

with n=2 changes into

1 2 3 4 5 6
7 8 9 10 11 12

Is there a simple way to do this?

Upvotes: 2

Views: 782

Answers (2)

High Performance Mark
High Performance Mark

Reputation: 78316

Suppose your original matrix is m, then:

reshape(m',[6 2])'

produces the required output. I'll leave it to you to generalise to other cases; comment or post again if that causes you problems.

Upvotes: 4

Squazic
Squazic

Reputation: 3690

This should work.

reshape(M',l/n,n)'

Where n is what you've defined and l is the total elements in M.

EDIT: Made it one-liner

Upvotes: 1

Related Questions