fscanfMat and fprintfMat functions

141 views
Skip to first unread message

Pierre

unread,
Oct 6, 2009, 4:11:43 AM10/6/09
to tumbi
Hello,

Would it possible to include easy-to-use matrix i/o functions in NSP
(like fscanfMat and fprintfMat in Scilab)? I know I can use "file"
objects and its functions like file.open[], etc., but fscanfMat was
really easier to use.

Thanks.

Pierre.

bruno

unread,
Oct 6, 2009, 8:18:09 AM10/6/09
to tumbi
In fact there is already fscanfMat in nsp (to be documented...)
and we could certainly add fprintfMat. Here is an nsp macro for this
job.
Note that it uses optional named argument so that if you want a
header comment and a format different from "%f" you will have
to enter :

A = rand(4,5)
fprintfMat( "toto.dat", A, header="my 4 x 5 random matrix",
format="%18.12e")

or

fprintfMat( "toto.dat", A, format="%18.12e", header="my 4 x 5 random
matrix")

hth
Bruno
=============================================
function fprintfMat(filename,mat,format="%f",header="")
// nsp shortcut for scilab fprintfMat
F = fopen(filename, mode="w")
if header ~= "" then
F.put_matrix[mat,format=format, title=header]
else
F.put_matrix[mat,format=format]
end
F.close[]
endfunction

Pierre

unread,
Oct 6, 2009, 11:30:22 AM10/6/09
to tumbi
Perfect. Thanks!

Pierre.

jpc

unread,
Oct 7, 2009, 1:14:28 AM10/7/09
to tumbi
Note that the fprintfMat given above can be shortened
by the use of varargopt and the (:) operator for hash table.

function fprintfMat(filename,mat,varargopt)
// nsp shortcut for scilab fprintfMat
F = fopen(filename, mode="w")
F.put_matrix[mat,varargopt(:)]
F.close[]
endfunction

Note also that the advantage of a manual use of put_ and get_matrix
is
the fact that you can store as many matrices you need in a file.

n=50;
a=rand(n,n,'u');
n=23;
b=rand(n,n,'u');

fd=fopen('TMPDIR/Mat',mode='w');
fprintf(fd,'Some text for a \n',);
fd.put_matrix[a]
fprintf(fd,'Some text for b \n',);
fd.put_matrix[b]
fd.close[];

fd=fopen('TMPDIR/Mat',mode='r');
[a1,txta1]=fd.get_matrix[];
[b1,txtb1]=fd.get_matrix[];
fd.close[];
if max(a1-a) > 1.e-1 then pause,end
if max(b1-b) > 1.e-1 then pause,end

jpc
Reply all
Reply to author
Forward
0 new messages