Splitting Up Large Matrix into n rows x 2 columns
Show older comments
I have a large matrix with n rows and 4 columns. I need to split the four columns into two separate matricies (each n rows by 2 columns) so that they can later be graphed x vs y.
Data sample:
Time Money Time Money
1 30 6 100
2 40 7 110
3 50 8 120
Ideally, I'd like this to be done for n rows and n columns, forming n number of smaller arrays. Any ideas? I saw similar questions, however the matricies were split with a set sized matrix, whereas the size of my matrix may change.
Answers (3)
Fangjun Jiang
on 14 Jul 2020
n=100;
a=rand(100,4);
x=a(:,1:2)
y=a(:,3:4)
Rohit Anand
on 14 Jul 2020
Assuming M is your matrix.
You can assign the splitted values to two different Matrices and then Plot them as needed.
MatA = M(:, 1:2) % All rows and first two columns assigned to MatA
MatB = M(:, 3:4) % All rows and the 3rd and 4th Column assigned to MatB
But There is no need to assign different variables to the splitted matrix. You can use M(:, 1:2) directly in your plot functions. This will keep the workspace clean.
4 Comments
k
on 14 Jul 2020
Rohit Anand
on 15 Jul 2020
Edited: Rohit Anand
on 15 Jul 2020
Yeah, Easily.
You want to split any number of columns in multiple matrices of two colums right?
You can do that,
Assuming M is the matrix
numCols = size(M, 2)
for i=1:2:numCols
x = M(:, i:i+1); % x is the temp matrix
% Do some operation on x like plot
end
This code will only work for Even Number of columns .But from the question I think that's exactly what numCols will be(even).
k
on 17 Jul 2020
Rohit Anand
on 19 Jul 2020
Can you post what you did? Cause the solution I suggested works just fine for me.
Rohit Anand
on 19 Jul 2020
For Splitting a matrix in a loop You can use the colon operator.
M(:, 3:4) % Select 3rd and 4th column of M and all rows
M(3:4, :) % 3rd and 4th row of M and all columns.
If you want to split any number of columns in multiple matrices of two colums, You can use a for loop to do so.
M = randi(27, 6, 24)
numCols = size(M, 2);
for i=1:2:numCols
x = M(:, i:i+1); % x is the temp matrix
disp(x);
end
This code snippet should solve your problem.

Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!