7

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
1
  • 1
    When using save as a function you need to do save( "-text", variableFilename, "myStruct"); i.e. all arguments are strings. Commented Aug 18, 2012 at 1:10

1 Answer 1

6

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer, it also contains the correct solution to my problem as JuanPi already said: I had to put the name of the struct inside" " when calling the save function. For saving such strings in a cell it is maybe more convenient to put them inside a struct and not a cell, because then the solution above also works and there is no need to handle the fileoutput on your own.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.