2

I have a dataset that includes all data in 1 column. However a new sub-dataset occurs every n rows. Using MATLAB, I need to grab each of these sub-datasets and place in a separate sequential column. For example, this:

Column 1

1
3
2
1
3
2
1
3
2

into this:

Column 1 | Column 2 | Column 3 | ...

1  1  1
3  3  3
2  2  2
tshepang
  • 12,111
  • 21
  • 91
  • 136
user3743235
  • 159
  • 8

1 Answers1

2

You can use the reshape command like so:

my_matrix = reshape(my_vector, num_rows, num_cols);

You can also replace num_cols in the above with [] to have MATLAB automatically figure out how many columns are needed to fit the data into num_rows rows. Similarly, you can replace num_rows with [] and have MATLAB figure out the number of rows needed to fit the data into num_cols columns.

Note that MATLAB will throw an error if my_vector does not contain exactly num_rows * num_cols elements. In other words, it will not pad with zeros or truncate your data if the sizes do not match.

Engineero
  • 12,340
  • 5
  • 53
  • 75
  • 1
    @user3743235 (OP) if you have in your last subdata-set less elements you could/should add a if-case or logical indexing to pad your data with `NaNs`. This has the advantage that, `NaNs`won't be missread as `0` data values and still the reshape would work for any data-set. You could do it with `if mod(numel(data),n)~=0...`. I wrote it as a comment because its just a little addition to @Engineero's solution. – The Minion Jun 16 '14 at 06:45
  • Ah, brilliant, just the tool I was looking for. Thanks for the additional point too. – user3743235 Jun 16 '14 at 21:47