every 4 rows of a table of n rows transposed into 4 new columns

8 ビュー (過去 30 日間)
Henry Clarke
Henry Clarke 2021 年 4 月 19 日
編集済み: Scott MacKenzie 2021 年 4 月 22 日
How do I retrieve every 4 rows of a table of n rows and transpose into 4 new columns
  1 件のコメント
the cyclist
the cyclist 2021 年 4 月 19 日
When you say "table", do you really mean the table data type? Or do you possibly mean some other data type, such as a numeric array, or a cell array? (People often use the language loosely.)
Can you upload the data, or a representative sample, in a MAT file?

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

回答 (1 件)

Scott MacKenzie
Scott MacKenzie 2021 年 4 月 21 日
編集済み: Scott MacKenzie 2021 年 4 月 22 日
Assuming (i) you are talking about a data matrix or a table data type converted to such and (ii) by "every 4 rows" you mean "every 4th row", this should work:
a=1:24;
a=reshape(a,[],3) % just a test data matrix
b = [];
for i=1:4
col=a(i:4:length(a),:);
b = [b reshape(col',[],1)];
end
b
Below is the output. Is this the desired result?
a =
1 9 17
2 10 18
3 11 19
4 12 20
5 13 21
6 14 22
7 15 23
8 16 24
b =
1 2 3 4
9 10 11 12
17 18 19 20
5 6 7 8
13 14 15 16
21 22 23 24
To avoid the for-loop, here's an alternate arrangement which yields the same output:
a=1:24;
a=reshape(a,[],3) % just a test data matrix
sortKey = repmat(1:4,1,length(a)/4);
b = [sortKey' a];
b = sortrows(b, 1);
b(:,1) = [];
b = reshape(b', [], 4)
This will only work If the number of rows in a is a multiple of 4. If that's not the case, you can pad a with rows of 0s to make up the deficit:
while rem(length(a),4) ~= 0
a = [a; zeros(1,size(a,2))];
end

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by