How to split a matrix columnwise and save each part as a matrix_part_i.txt file using a loop?
조회 수: 1 (최근 30일)
이전 댓글 표시
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:
clear;
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
TOTAL_NUMBER_OF_COLUMNS=size(X,2);
NUMBER_OF_COLUMNS_PER_PART=TOTAL_NUMBER_OF_COLUMNS/NUMBER_OF_OUTPUT_P
ARTS;
for p=1:NUMBER_OF_OUTPUT_PARTS;
Xp{p}=X(:,
((p-1)*NUMBER_OF_COLUMNS_PER_PART)+1:NUMBER_OF_COLUMNS_PER_PART*p);
%Partition of main matrix into 2 parts
end;
%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:
Xp{p}=X(:,
((p-1)*NUMBER_OF_COLUMNS_PER_PART)+1:NUMBER_OF_COLUMNS_PER_PART*p);
fid = fopen('Xp{p}.txt', 'wt');
fprintf(fid, [repmat('%g\t', 1, size(Xp{p},2)-1) '%g\n'], Xp{p}.');
fclose(fid);
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
Emerson
댓글 수: 1
Oleg Komarov
2011년 5월 8일
Please read this tutorial: http://www.mathworks.com/matlabcentral/answers/6200-tutorial-how-to-ask-a-question-on-answers-and-get-a-fast-answer
채택된 답변
Walter Roberson
2011년 5월 8일
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');
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!