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

3 vues (au cours des 30 derniers jours)
Eric Roden
Eric Roden le 25 Fév 2023
Commenté : Adam Danz le 27 Fév 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 commentaires
Stephen23
Stephen23 le 27 Fév 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 le 27 Fév 2023
formattedDisplayText may come in handy.

Connectez-vous pour commenter.

Réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by