TXT File Population with Arrays and Text

1 view (last 30 days)
MATLAB_Soldier
MATLAB_Soldier on 7 Nov 2022
Commented: Mathieu NOE on 16 Nov 2022
Hi all,
I have a script that does some data manipulation.
After the data manipulation, I would like to save everything in a txt file. The data I am trying to add to txt file is stored in different arrays in MATLAB, around 15-20 arrays. There are two types, single line and multiple line arrays, as follows:
A=[1,1,1,1,1];
B=[2,2,2];
C=[1,1,1,1,1;2,2,2,2,2;3,3,3,3,3];
I also would like to add some text to this txt file and it should be in the following form:
Text1Text1Text1Text1Text1Text1Text1Text1Text1 + TODAYS DATE
Text2Text2Text2Text2Text2Text2Text2
[1,1,1,1,1]
Text3Text3Text3Text3Text3Text3Text3
[2,2,2]
Text4Text4Text4Text4Text4Text4Text4
[1,1,1,1,1;2,2,2,2,2;3,3,3,3,3]
.......
The text will always be the same but the arrays will change. It is very important to add the brackets at each end of the array.
What is the best way to approach this problem?
I presume writematrix command is not suitable. I was thinking maybe, fprintf could work.
Many thanks.

Answers (1)

Mathieu NOE
Mathieu NOE on 7 Nov 2022
hello
maybe not the cleanest code but writecell make this doable without to much headaches
% export results to txt
filename_export='myfile.txt';
%% main loop
A='[1,1,1,1,1]';
B='[2,2,2]';
C='[1,1,1,1,1;2,2,2,2,2;3,3,3,3,3]';
datenow = date;
sheet=1; % NB : all data on 1st sheet (use append writte mode)
L1={'Text1','Text1','Text1','Text1','Text1','Text1','Text1','Text1',datenow};
L2={' '};% empty line
L3={'Text2','Text2','Text2','Text2','Text2'};
L4={'Text3','Text3','Text3','Text3','Text3'};
L5={'Text4','Text4','Text4','Text4','Text4'};
writecell(L1,filename_export,"Delimiter","tab");
writecell(L2,filename_export,"Delimiter","tab","Writemode",'append'); % add empty line
writecell(L3,filename_export,"Delimiter","tab","Writemode",'append');
writematrix(A,filename_export,"Delimiter","tab","Writemode",'append');
writecell(L2,filename_export,"Delimiter","tab","Writemode",'append'); % add empty line
writecell(L4,filename_export,"Delimiter","tab","Writemode",'append');
writematrix(B,filename_export,"Delimiter","tab","Writemode",'append');
writecell(L2,filename_export,"Delimiter","tab","Writemode",'append'); % add empty line
writecell(L5,filename_export,"Delimiter","tab","Writemode",'append');
writematrix(C,filename_export,"Delimiter","tab","Writemode",'append');
result :
Text1 Text1 Text1 Text1 Text1 Text1 Text1 Text1 07-Nov-2022
Text2 Text2 Text2 Text2 Text2
[1,1,1,1,1]
Text3 Text3 Text3 Text3 Text3
[2,2,2]
Text4 Text4 Text4 Text4 Text4
[1,1,1,1,1;2,2,2,2,2;3,3,3,3,3]

Categories

Find more on File Operations in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!