Question regarding writing data to txt file

1 回表示 (過去 30 日間)
jana
jana 2014 年 10 月 26 日
コメント済み: Azzi Abdelmalek 2014 年 10 月 26 日
Hi,
I have the following matrices:
A = [10,8,6;1,4,5]
B = [3,4,7;8,9,10]
I would like to print my data to a txt file that displays the name of the matrix, followed by row and column index of the data followed by the specific value for that column and row. For example:
A,1,1,10,1,2,8,1,3,6,2,1,1,2,2,4,2,3,5
B,1,1,3,1,2,4,1,3,7,2,1,8,2,2,9,2,3,10
Please help!..I am new to matlab

採用された回答

Image Analyst
Image Analyst 2014 年 10 月 26 日
This should be rather straightforward and easy to understand. If not, ask.
A = [10,8,6;1,4,5]
B = [3,4,7;8,9,10]
fid = fopen('delete_me.txt', 'wt');
% Print out the line for A
[rows, columns] = size(A);
fprintf(fid, 'A');
for col = 1 : columns
for row = 1 : rows
fprintf(fid, ',%d,%d,%d', row, col, A(row, col));
end
end
% Now for the B matrix.
[rows, columns] = size(B);
fprintf(fid, '\nB');
for col = 1 : columns
for row = 1 : rows
fprintf(fid, ',%d,%d,%d', row, col, B(row, col));
end
end
fclose(fid);
% In the file, there should be this:
% A,1,1,10,1,2,8,1,3,6,2,1,1,2,2,4,2,3,5
% B,1,1,3,1,2,4,1,3,7,2,1,8,2,2,9,2,3,10

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 10 月 26 日
A = [10,8,6;1,4,5]
[n,m]=size(A)
[ii,jj]=ind2sub(size(A),1:numel(A))
iA=reshape(ii,n,m)'
jA=reshape(jj,n,m)'
A=A'
s1=sprintf('%d,%d,%d,',[iA(:)';jA(:)';A(:)'])
  2 件のコメント
jana
jana 2014 年 10 月 26 日
Thank you! but, using sprintf I cannot print my data to a txt file. Is there any other command that I can use?
Azzi Abdelmalek
Azzi Abdelmalek 2014 年 10 月 26 日
A = [10,8,6;1,4,5]
[n,m]=size(A)
[ii,jj]=ind2sub(size(A),1:numel(A))
iA=reshape(ii,n,m)'
jA=reshape(jj,n,m)'
A=A'
fid=fopen('file.txt','w')
fprintf(fid,'%d,%d,%d,',[iA(:)';jA(:)';A(:)'])
fclose(fid)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCall Web Services from MATLAB Using HTTP についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by