필터 지우기
필터 지우기

Write data .txt format with different vector in different column

조회 수: 21 (최근 30일)
krai
krai 2018년 7월 3일
편집: krai 2018년 7월 4일
I have two different single column matrix
A = [1 2 3 4 5 6 7]; B = [110 120 114 116 117 119 121];
I want to write it in the .txt format as shown below,
1 110
2 120
3 114
4 116
5 117
6 119
7 121
Now I am try to do it with the below mentioned code but I am getting all the data in a single column,
fid=fopen('MyFile.txt','wt');
fprintf(fid,'%d\r\n',A);
fprintf(fid,'%d\r\n',B);
fclose(fid);

채택된 답변

Mridul G
Mridul G 2018년 7월 3일
A = [A B];
fid=fopen('MyFile.txt','wt');
for i = 1:length(A)
fprintf(fid,'%d %d\n',A(i,1),A(i,2));
end
fclose(fid);
  댓글 수: 3
Guillaume
Guillaume 2018년 7월 3일
I think Mridul assumed that A and B were column vectors as you've stated whereas you've got row vectors. So instead of creating a Nx2 matrix, [A B] creates a row vector. That can easily be fixed with
A = [A; B];
and iterating over the columns instead of rows.
But it's also a waste of time. You don't need a loop.
@Mridul, note that length should never be used on a matrix. Always use size with an explicit dimension.
krai
krai 2018년 7월 3일
Thanks works as required..

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Guillaume
Guillaume 2018년 7월 3일
A loop is a waste of time:
fid = fopen('MyFile.txt', 'wt');
fprintf(fid, '%d %d\n', [A; B]);
fclose(fid);
This assumes that A and B are row vectors as you've shown but not as you've stated. A and B must of course have the same number of elements.
I assumeed you wanted a space between each column.
  댓글 수: 2
Stephen23
Stephen23 2018년 7월 3일
+1 no loop is the way to go.
krai
krai 2018년 7월 3일
편집: krai 2018년 7월 4일
Thanks Guillaume, Yes you assumed correct, I want space between each column.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by