How to add headers to an array and output to a text file?
4 views (last 30 days)
Show older comments
I have an array of numbers of type double. Each row is of length 3xN where N is some fixed number. I want to reshape each row as a sub-array of length N x 3 with the header THIS IS SUB-ARRAY: x, where x is the number of the sub-array. Finally, I want to output as a text file. For example, the given data (attached) I want to have:
THIS IS SUB-ARRAY: 1
0.814723686393179 0.913375856139019 0.278498218867048
0.964888535199277 0.957166948242946 0.141886338627215
0.792207329559554 0.0357116785741896 0.678735154857774
THIS IS SUB-ARRAY: 2
0.905791937075619 0.632359246225410 0.546881519204984
0.157613081677548 0.485375648722841 0.421761282626275
0.959492426392903 0.849129305868777 0.757740130578333
THIS IS SUB-ARRAY: 3
0.126986816293506 0.0975404049994095 0.957506835434298
0.970592781760616 0.800280468888800 0.915735525189067
0.655740699156587 0.933993247757551 0.743132468124916
I think I can do the reshaping of each row by something like
[nrow,ncol] = size(x);
for i = 1:nrow
A = x(i,:);
B = reshape(A, [ncol,3]);
end
But how do I add the header and output to a text file?
0 Comments
Answers (1)
Walter Roberson
on 15 Jan 2023
One way:
Put the various values into a cell array, and then writecell()
Another way:
Construct a string array from the various lines, and then writelines()
Third way: fopen(), loop using fprintf() to write header and contents; afterwards fclose()
0 Comments
See Also
Categories
Find more on Cell Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!