Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a struct to a file using a variable filename in Octave?

In Octave I would like to save a struct to a textfile where the name of the file is decided during the runtime of the script. With my approach I always get an error:

expecting all arguments to be strings. 

(For a fixed filename this works fine.) So how to save a struct to a file using a variable filename?

clear all;
myStruct(1).resultA = 1;
myStruct(1).resultB = 2;
myStruct(2).resultA = 3;
myStruct(2).resultB = 4;

variableFilename = strftime ("result_%Y-%m-%d_%H-%M.mat", localtime(time()))

save fixedFilename.mat myStruct; 
% this works and saves the struct in fixedFilename.mat

save( "-text", variableFilename, myStruct); 
% this gives error: expecting all arguments to be strings
like image 744
marco Avatar asked Aug 17 '12 14:08

marco


People also ask

How do I import files into Octave?

data = load('-ascii','autocleaned. txt'); Loaded the data as wanted in to a matrix in Octave. Since all the data is in fixed width columns (except the last strings), you should be able to read it line by line, using fscanf to decode the line.

Which of the following is used to read data from a file in Octave?

Octave provides the scanf , fscanf , and sscanf functions to read formatted input. There are two forms of each of these functions. One can be used to extract vectors of data from a file, and the other is more `C-like'. In the first form, read from fid according to template , returning the result in the matrix val .


1 Answers

In Octave, When using save as a function you need to do something like this:

myfilename = "stuff.txt";
mystruct = [ 1 2; 3 4]
save("-text", myfilename, "mystruct");

The above code will create a stuff.txt file and the matrix data is put in there.

The above code will only work when mystruct is a matrix, if you have a cell of strings, it will fail. For those, you can roll your own:

 xKey = cell(2, 1);
 xKey{1} = "Make me a sandwich...";
 xKey{2} = "OUT OF BABIES!";
 outfile = fopen("something.txt", "a");
 for i=1:rows(xKey),
   fprintf(outfile, "%s\n", xKey{i,1});
 end
 fflush(outfile);
 fclose(outfile);
like image 166
Eric Leschinski Avatar answered Oct 27 '22 00:10

Eric Leschinski