MATLAB Answers

How to change array format - change row number and column number, but have all the data as before

19 views (last 30 days)
Hi everyone,
I am interested in following if I put as an example;
I have an array A;
1 1 1 1
1 1 1 1
1 1 1 1
2 2 2 2
2 2 2 2
2 2 2 2
3 3 3 3
3 3 3 3
3 3 3 3
Now I would like to change this to array B which would look like;
1 1 1 1 2 2 2 2 3 3 3 3
1 1 1 1 2 2 2 2 3 3 3 3
1 1 1 1 2 2 2 2 3 3 3 3
How can I do this type of thing on matlab? The array A can have much more sets of data, and the code must go through each row of A until there is no more data.
Thanks a lot in advance! Sara

  0 Comments

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 1 Jun 2018
Edited: Stephen Cobeldick on 1 Jun 2018
Depending on the required element order, (along 2nd dim first):
B = reshape(A.',3,[])
or (along 1st dim first):
B = reshape(permute(reshape(A,3,[],4),[1,3,2]),3,[])
or (along 1st dim first):
cell2mat(mat2cell(A,[3,3,3],4).')

  4 Comments

Show 1 older comment
SNT
SNT on 1 Jun 2018
Hi Stephen, also I get an error with the 3rd option;
C = cell2mat(mat2cell(A,[3,3,3],4).');
Error using mat2cell (line 97)
Input arguments, D1 through D2, must sum to each dimension of the input matrix
size, [15 4].'
How can I get the output I have stated in my comment above?
Thanks a lot!
Sara
Stephen Cobeldick
Stephen Cobeldick on 1 Jun 2018
>> reshape(permute(reshape(A.',size(A,2),2,[]),[2,1,3]),2,[])
ans =
0.547009 0.744693 0.686775 0.368485 0.780227 0.929386 0.486792 0.446784 0.508509 0.817628 0.644318 0.811580 0.350727 0.875943 0.622475
0.296321 0.188955 0.183511 0.625619 0.081126 0.775713 0.435859 0.306349 0.510772 0.794831 0.378609 0.532826 0.939002 0.550156 0.587045
SNT
SNT on 1 Jun 2018
Hi Stephen,
The second option
B = reshape(permute(reshape(A,3,[],4),[1,3,2]),3,[])
Seems to work great! Thanks

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!