필터 지우기
필터 지우기

How to write to csv file in shortG format?

조회 수: 3 (최근 30일)
slavnikp
slavnikp 2024년 5월 7일
댓글: slavnikp 2024년 5월 8일
Hello,
I would like to save a Matlab table (first column strings, the rest are floating numbers) to a csv in the shortG format. I have set the format in my script and when I look at the table in the program, it looks just as it should. However, when I save the table to a csv file, the numbers increase their decimal places counts suddenly, forbidding numbers like -6.0247e-06 etc. How to overcome this, please?
Thank you all in advance.

채택된 답변

Stephen23
Stephen23 2024년 5월 8일
Here is one approach that gives exactly the shortG format in your CSV file:
format long G
M = rand(3,5);
M(1) = -6.0247123456789e-06
M = 3x5
-6.0247123456789e-06 0.197674571707108 0.0250170842766982 0.310389529607936 0.506567531163724 0.908509002122202 0.204247079115749 0.25809728620882 0.771847731508226 0.391636786365166 0.245969238812545 0.0773711174826793 0.563422695499417 0.0640169158863244 0.345928545312606
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
F = @(v)formattedDisplayText(v,'NumericFormat','shortG');
S = regexprep(arrayfun(F,M),{'\s+','\.{3}'},'');
writelines(join(S,','),'mytest.csv')
Checking the file content:
type mytest.csv
-6.0247e-06,0.19767,0.025017,0.31039,0.50657 0.90851,0.20425,0.2581,0.77185,0.39164 0.24597,0.077371,0.56342,0.064017,0.34593
  댓글 수: 3
Stephen23
Stephen23 2024년 5월 8일
"However, it is very slow for larger matrix dimension."
Yes, it will be slow. If you want fast file writing then either use WRITEMATRIX or FPRINT (you can specify the format with e.g. fixed fractional digits or significant figures). But because your question specified that you wanted exactly short G format, then you will have to convert this to text using something like what I showed in my answer, which will generally be slower than writing numeric data directly to the file.
Basically your stated requirement forces you into have slow code.
slavnikp
slavnikp 2024년 5월 8일
Sure, I understand, thank you.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by