简体   繁体   中英

fprintf for large matrix in matlab

I am trying to fprintf with a large matrix (1500x100 type of dimensions). I tried this:

for i=1:1500
      fprintf(filename,'%s %f \n', words_cell{i}, polS_matrix(i,:));
end

But I don't know how to write the %s %f part, because my matrix is a length 100 and it would be very troublesome to write 100 %f . Is there any way to do this easily? I have look in the matlab fprintf page, but I don't see anything that I can use.

You could use a nested sprintf for the matrix:

sprintf('%f ', polS_matrix(i,:))

This implicitly takes all the matrix elements even if there is only one %f , producing a string from all the numbers in row i .

You may also want to change the iteration index name to avoid shadowing the imaginary unit.

So, the code would be:

for k = 1:1500
    fprintf(filename,'%s %s \n', words_cell{k}, sprintf('%f ', polS_matrix(k,:)));
end

How about

for i=1:1500
      fprintf(filename,strcat('%s ', repmat('%f ',1,100), ' \n'), words_cell{i}, polS_matrix(i,:));
end

or, for performance:

formatSpecifiersString = strcat('%s ', repmat('%f ',1,100), ' \n');
for i=1:1500
      fprintf(filename, formatSpecifiersString, words_cell{i}, polS_matrix(i,:));
end

[ edit: added space in repmat('%s'..) --> repmat('%f '..) ]

I would rely on the vetorized nature of fprintf and use three separate calls to the file stream:

for i=1:size(polS_matrix,1)
    fprintf(filename ,  '%s' , words_cell{i});
    fprintf(filename , ' %f' , polS_matrix(i,:));
    fprintf(filename , '\n');
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM