Matlab fprintf正确格式说明符,用于四舍五入到14个小数位 [英] Matlab fprintf correct format specifier for rounding to 14 decimal places

查看:2876
本文介绍了Matlab fprintf正确格式说明符,用于四舍五入到14个小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面提供的代码来读取矩阵,并在每个值的末尾应用分号(; )和换行符。

I am using the code presented below to read a matrix and apply a semicolon (;) and newline at the end of every value.

我有精度格式说明符的问题。代码块下面是csv输出中的一行。您可以看到第5列和第6列格式正确,但有指数值,我需要四舍五入到14个小数位。为什么第4行的'%f.14'不是这样做的?

I am having problems with the precision format specifier. Below the code block is a line from the csv output. You can see that columns 5 and 6 are formatted properly, but there are exponential values that I need rounded to 14 decimal places. Why isn't the '%f.14'on line 4 doing this? I thought it didn't use exponential notation?

function write_to_csv(filepath, decision)
    csv = fopen('matrix.csv', 'a+');
    for ii = 1:length(decision)
        format = '%d; %f.14';
        fprintf(csv, format, decision(ii));
    end 
    fprintf(csv,'\n')
    fclose(csv);
end

1; 1.032204e-03; -2.580511e-04; 1; 32190201170708; 17682101210450; 2; 7.600000e-01; -1;

1; 1.032204e-03; -2.580511e-04; 1; 32190201170708; 17682101210450; 2; 7.600000e-01; -1;

向MChandler提供上述代码的问题:

Credit to MChandler for supplying the above code from question: Add a delimiter to end of each line of csv file MATLAB

推荐答案

这取决于变量 decision 的格式。由于在%f.14 之前有%d ,它将渲染一维矩阵为%d 。它将完全忽略定点格式说明符。如果你的矩阵决定确实是一维的,使用 format ='%.14f'; 如注释中所述:

This depends on the format of the variable decision. Since you have %d before the %f.14 it will render a 1-dimensional matrix as only %d. It will completely ignore the fixed point format specifier. If your matrix decision is indeed 1-dimensional, use format = '%.14f'; as mentioned in the comments:

function write_to_csv(filepath, decision)
    csv = fopen('matrix.csv', 'a+');
    for ii = 1:length(decision)
        format = '%.14f';
        fprintf(csv, format, decision(ii));
    end 
    fprintf(csv,'\n')
    fclose(csv);
end

您可以在这里阅读格式说明符: https://www.mathworks.com/help/matlab/matlab_prog/formatting-strings .html#bq0z60p-1

You can read up on format specifiers here: https://www.mathworks.com/help/matlab/matlab_prog/formatting-strings.html#bq0z60p-1

这篇关于Matlab fprintf正确格式说明符,用于四舍五入到14个小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆