# Split a row into several rows

79 ビュー (過去 30 日間)
Olu adroit 2016 年 1 月 14 日
コメント済み: Olu adroit 2016 年 1 月 14 日
Hi all, I am trying to split a single-row matrix say for example
A = [1,2,3,4,17,18,19,20,33,34,35,36,49,50,51,52,65,66]
into a multiple-row matrix B, the maximum number of columns in B being 5. I would expect to get something like
B = [1,2,3,4,17;18,19,20,33,34;35,36,49,50,51;52,65,66]
I tried using the reshape function as below but it's giving an error saying
Product of known dimensions, 5, not divisible into total number of elements, 18
Please any suggestion would be appreciated.
%
% I would like to get
% B = 1 2 3 4 17
% 18 19 20 33 34
% 35 36 49 50 51
% 52 65 66
%
% code
A = [1,2,3,4,17,18,19,20,33,34,35,36,49,50,51,52,65,66];
B = reshape(A, 5, []);

サインインしてコメントする。

### 採用された回答

Stephen 2016 年 1 月 14 日

A matrix cannot have gaps or missing values: every row must be the same length, just as every column must too. So you will have to join some values onto A before reshaping it:
>> N = 5;
>> reshape([A,nan(1,N-mod(numel(A),N))],[],N)
ans =
1 17 33 49 65
2 18 34 50 66
3 19 35 51 NaN
4 20 36 52 NaN
##### 2 件のコメント表示非表示 1 件の古いコメント
Olu adroit 2016 年 1 月 14 日
ok i got it now. I substituted NaN with zeros. Thanks

サインインしてコメントする。

### その他の回答 (1 件)

Ilham Hardy 2016 年 1 月 14 日
The error message indicates the error very clear. What will be the dimension of the B matrix then? 5x4.9 matrix?
Unless you pad the A matrix beforehand with
A = [A,NaN,NaN];
the reshape command will not works (obviously).

サインインしてコメントする。

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by