How to begin? Text based matrix.

6 次查看(过去 30 天)
Mark Kamps
Mark Kamps 2017-8-28
评论: Jan 2017-8-28
I have a question regarding setting up a Matrix that is composed of text and calculations.
I want to create a file, or simply copy the output of MATLAB to use in a different program. Ideally a simple .txt file is the output. It should contain lots of rows of text (>10.000) with simple numbers. The value of these numbers are the result of calculations. There should also be several headers and sometimes a blank row.
Suppose I want to create the following:
Bonds
1 1 1 2
2 1 1 3
3 1 1 4
...
7515 1 1534 1675
7516 2 1534 1676
Where the columns represent the numbers which are calculated within the script. I want to create the entire file in one or multiple for loops, but I do not know how to start.
For instance, the following code gives an error (Subscripted assignment dimension mismatch.), since the entries have different lengths:
FILE(1,:) = [sprintf('Bonds')];
FILE(3,:) = [sprintf(n,t,'1 2')];
FILE(4,:) = [sprintf(n,t,'1 3')];
FILE(5,:) = [sprintf(n,t,'1 4')];
If I change to for instance a cell type it will change the layout to a EXCEL like structure. How should I proceed? What is the easiest structure to begin with?
  2 个评论
Stephen23
Stephen23 2017-8-28
"..I do not know how to start"
Start by searching this forum, where there are hundreds of questions and answers related to writing text files, and how to format them.
Read the MATLAB documentation.
Break the problem into parts, solve each part.
Jan
Jan 2017-8-28
Note that
FILE(1,:) = [sprintf('Bonds')];
is the same as
FILE(1,:) = 'Bonds';
and that the readers cannot know, what sprintf(n,t,'1 2') is, as long as "n" and "t" are not explained. The intention of "FILE(1,:)" is not clear also.
You cannot compose a "matrix" out "of text and calculations". So start with a cup of coffee. Then write down, how the wanted file format is defined.

请先登录,再进行评论。

回答(1 个)

KSSV
KSSV 2017-8-28
doc fprintf. YOu can open a text file and write data line by line into it. Check the below example code:
fid = fopen('test.txt','w') ; % open file to write
fprintf(fid,'%s \n','Bonds') ; % write a string
for i = 1:10
K = rand(1,randperm(10,1)) ; % write some random data
fs = repmat('%f',1,length(K)) ;
fprintf(fid,strcat(fs,'\n'),K);
end
fclose(fid) ; % close the file

类别

Help CenterFile Exchange 中查找有关 Workspace Variables and MAT Files 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by