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

17 views (last 30 days)
Henry Clarke on 19 Apr 2021 at 15:38
Edited: Scott MacKenzie on 22 Apr 2021 at 9:30
How do I retrieve every 4 rows of a table of n rows and transpose into 4 new columns
##### 1 CommentShowHide None
the cyclist on 19 Apr 2021 at 16:08
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?

Scott MacKenzie on 21 Apr 2021 at 19:14
Edited: Scott MacKenzie on 22 Apr 2021 at 9:30
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