user494461
user494461

Reputation:

How to append a matrix to a new line in a file in matlab?

I have a 10x1 matrix of integer values in matlab, how do I write this to a line *text* file? I am in a loop and want to append more than 500 such matrices, each on a new line.

fileID = fopen('exp.txt','a');

[r,c] = size(newFinalTree);
for i=1:r
    j=1;
    val=newFinalTree(i,j);
    while val~=0
       temp=reprVectors(val,:); %%%write this matrix to the file
       fprintf(fileID,temp); %%%this line produces error saying invalid format
       j=j+1;
       val=newFinalTree(i,j);
    end    
end
fclose(fileID);

Also what is the best way to write such a matrix so that reading the text file from a c code will be easy?

Upvotes: 0

Views: 2623

Answers (3)

Christian Reimer
Christian Reimer

Reputation: 445

If you want to store true matrices, mat2str(...) is your friend. You could replace:

fprintf(fileID,temp); %%%this line produces error saying invalid format

with:

fprintf(fileID,'%s\n',mat2str(temp))

or, if you want the line in your text file to be temp = (some matrix):

fprintf(fileID,'temp = %s\n',mat2str(temp));

Reading them in C should be easy, using fscanf(...) and keeping in mind that the matrix delimiters are [], the line delimiters are ; and the column delimiters are spaces.

Upvotes: 0

denahiro
denahiro

Reputation: 1199

I think the best way to do this would be to concatenate your matrices into a 500x10 matrix and then use dlmwrite.

input=randi(100,500,10);

dlmwrite(outputFilename,input)

This is much less error prone than writing it yourself and it's also much faster.

If the format doesn't suit you dlmwrite has the possibility to change the delimiter.

Another advantage of dlmwrite compared to fprintf is that dlmwrite automatically selects the correct formatting for your input data.

Upvotes: 2

Dan
Dan

Reputation: 45752

if reprVectors() is outputting that 10x1 you're talking about then try this small change:

fprintf(fileID, "%d %d %d %d %d %d %d %d %d %d", temp);

Upvotes: 0

Related Questions