print 1-D array to file as 2-D matrix

2 visualizaciones (últimos 30 días)
Eric Roden
Eric Roden el 25 de Feb. de 2023
Comentada: Adam Danz el 27 de Feb. de 2023
Dear colleagues:
I have a 1-D array, named pvar, where contains the "primary variables" generated in a method-of-lines PDE simulation of a one-dimensional advection-diffusion-reaction system. pvar has nx npde columns, where nx is the number of node points in the one-dimensional spatial domain, and npde is the number of PDEs in the system. I would like to print pvar out as 2-D matrix, row by row to a text file, along with 1-D array x that contains the node points for the one-dimensional spatial domain. An updated version of pvar is generated at each time step in the simulation, and I want to print that updated array along with x at selected output times using the outputfcn in the Matlab ODE solvers. I have done this type of print-to-file in Fortran versions of this same type of simulation using the following statement:
do i=1,nx
j=npde * i
write(1,*) x(i),(pvar(j-k)),k=(npde-1),0,-1)
end do
where the statement pvar(j-k)),k=(npde-1),0,-1 writes the values for each PDE, going left to right, for each node point going down through the nx nodes points in sequence.
What I don't know how to do is to code this statement in Matlab. The first thing I tried was
for i=1:nx
j=npde*i;
fprintf(fid,'%g\t',x(i),pvar(j-(npde-1):-1:0);
end
Which returns the error statement "Array indices must be positive integers or logical values"
I'm not sure if there is a vectorized coding structure available in Matlab which does the same thing as that in Fortran, but if there is, could some one please enlighten me?
Many thanks,
Eric Roden
Professor of Geoscience
University of Wisconsin-Madison
  3 comentarios
Stephen23
Stephen23 el 27 de Feb. de 2023
"I'm not sure if there is a vectorized coding structure available in Matlab which does the same thing as that in Fortran,"
The general MATLAB approach is to use arrays, not to write lots of nested loops. As far as I can tell you have a matrix: then probably all you need is transpose/reshape or similar, and then one FPRINTF call.
Adam Danz
Adam Danz el 27 de Feb. de 2023
formattedDisplayText may come in handy.

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by