How to repshape array to matrix with different length of each row ?

Lets assume we have array M with size 1*100
M= [1 2 3 4 5 6 7 8 9 0 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 9 2 ....]
I need to rephase it to B matrix that have 12 rows with max column 9
B = [1 2 3 4 5 6 7 8 9 ; 0 1 1 1 1 1 1 1 NAN ; 1 1 2 2 2 2 2 2 9 2; ... etc]
if we notice the first row is 1*9
second row is 1*8
third row is 1*10
and so on until we fill all the 12 rows. The sizes for the rows [9 8 10 8 9 8 8 8 8 9 8 7]
I just make up this example becuase my array is too long and I need to divid it depend on three numbers which is 28, 31,30
I tried to make if loop to implmemt it but I cannot it's completely worng.

 Accepted Answer

MATLAB has the function reshape, but there are a couple things to be aware of when using it:
  1. The number of elements can't change, meaning the product of the dimensions of your array have to exactly match the product of the dimensions of your array.
  2. Each row/column will have the same number of elements (unless you want to get into cell arrays)

6 Comments

I know it but it does not work for me since I have different length of rows. However, different length does not mean I will not have any elements to match the maximum row length.
Just think if I initialize B matrix by using B=zeros(12,9). then just fill the B matrix but M elements using the for loop with some conditions for the length
That's true. You can also initialize a matrix of NaN's, which might be better since 0 is a valid entry (at least in your example).
What I don't understand is how you know where to cut your vector. Could you explain?
Yes. I have three size that I need each row to have 8 , 9 , and 10. this is just for the made up example mentioned about. This number has know sequence for me for my orginal probelm.
You are right. I need to include the length for all vectors
[9 8 10 8 9 8 8 8 8 9 8 7]
RowS=1
RowE=0
for i=1:1:12
RowE=RowE+MDN(i);
Divided_LD(i,:)=LD(RowS:RowE)
RowS=RowS+RowE;
end
I have error
MDN is the length of each row
Unable to perform assignment because the size of the left side is 1-by-744 and the size of the right side is 1-by-672.
This is for my M-file the main array too long for the orginal M-file
Here's a sample assuming the vector is 1x100
% Create dummy data
test = randi(20,[1 100]);
brks = [9 8 10 8 9 8 8 8 8 9 8 7]
ind = [0 cumsum(brks)]
% preallocate vector with NaNs
matrix = nan([12 max(brks)])
for r = 1:length(brks)
matrix(r,1:brks(r)) = test((ind(r)+1):ind(r+1));
end

Sign in to comment.

More Answers (0)

Categories

Asked:

on 22 Mar 2020

Commented:

on 22 Mar 2020

Community Treasure Hunt

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

Start Hunting!