fprintf function applied to 3D matrices

2 views (last 30 days)
Hi guys, I'm struggling a bit with fprintf function. I have a 3D matrix A(m,n,k); m,n are properties and k is a time step. I would like to print the matrix in the format A(m,n,1) A(m,n,2) A(m,n,3) and so on till k. I though to create a big 2D matrix and then print it but I was wondering if there is a more elegant solution.
Thank you very much for your help, Gabriele
  2 Comments
Walter Roberson
Walter Roberson on 5 Aug 2015
Are the first two lines to be
A(1,1,1) A(1,1,2) A(1,1,3) ... A(1,1,k)
A(2,1,1) A(2,1,2) A(2,1,3) ... A(2,1,k)
?
Gabriele Granello
Gabriele Granello on 6 Aug 2015
Edited: Gabriele Granello on 6 Aug 2015
The lines are
A(1,1,1) A(1,2,1)------A(1,n,1) A(1,1,2) A(1,2,2)---------A(1,n,2)
A(2,1,1) A(2,2,1)------A(2,n,1) A(2,1,2) A(2,2,2)---------A(2,n,2) ecc

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 5 Aug 2015
permute() the array so that the dimension to be printed across is down the columns. Create a format by
numcol = 17; %as appropriate
colfmt = '%13.5f'; (or appropriate format)
fmt = [repmat([colfmt ' '], 1, numcol), colfmt, '\n'];
Then
fprintf(fid, fmt, PermutedArray)
  5 Comments
Gabriele Granello
Gabriele Granello on 6 Aug 2015
I have used the less elegant solution for the moment. But now i will try playing with the permutation because seems an interesting function and jumping between 2D or 3D quite easy would be beneficial for my code. Thanks for your help
Walter Roberson
Walter Roberson on 6 Aug 2015
numcol = size(A,2) * size(A,3);
fmt = [repmat([colfmt ' '], 1, numcol-1), colfmt, '\n'];
Note: if you don't mind an extra space at the end of the line, then
fmt = [repmat([colfmt ' '], 1, numcol), '\n'];

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!