How to split a matrix columnwise and save each part as a matrix_part_i.txt file using a loop?

1 view (last 30 days)
I want to split a matrix column-wise and
save each part with correct index.
The begin and end of each part is determined by a
parameter p as coded below:
X=rand(5,10); %Let M be a matrix with 10 columns
NUMBER_OF_OUTPUT_PARTS=2; %Let 2 be the amount of parts of a matrix
%Partition of main matrix into 2 parts
%Output is two matrices each with 5 columns, as expected!!!
Since A=Xp{1,1} gives the first part
and B=Mp{1,2} the second part and so on,
I thought that I could automatically save all parts within the same
code by writing the following lines within the loop:
fid = fopen('Xp{p}.txt', 'wt');
fprintf(fid, [repmat('%g\t', 1, size(Xp{p},2)-1) '%g\n'], Xp{p}.');
Unfortunately it did not work.
So I wounder if someone knows what I should do to extract each part
of main matrix and save automatically within the loop with the
correct index without overwriting.
Thank you in advance for your help
  1 Comment
Oleg Komarov
Oleg Komarov on 8 May 2011
Please read this tutorial:

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 8 May 2011
You would probably find it easier to use mat2cell() to split the matrix.
In your line
fid = fopen('Xp{p}.txt', 'wt');
you are using the same output file name each time. Perhaps you want something like,
fid = fopen(sprintf('X_%d.txt',p),'wt');
  1 Comment
Emerson De Souza
Emerson De Souza on 8 May 2011
Thank you Walter,
your suggested line solved the problem.
Later I will try the advantages of using mat2cell() to split the matrix and compare with the current commands.
I wish you a nice weekend

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by