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
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.
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 .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With