MATLAB: Does the SAVE command with the -ascii option not honor the ordering of variables in MATLAB 7.0 (R14)

asciiMATLABorderorderingsave

I am trying to use the SAVE command to write variables in the MATLAB workspace to an ASCII text file. However, the ordering of the variables in the file appears to be independent of the ordering of the variables in the command.
For example, the ordering in the files generated by the commands below are the same:
x=1;y=2;z=3;
save('test1.txt','x','y','z','-ascii');
save('test2.txt','x','z','y','-ascii');
save('test3.txt','z','x','y','-ascii');

Best Answer

This bug has been fixed for Release 14 SP1 (R14SP1). For previous releases, please read below for any possible workarounds:
This is a bug in MATLAB 7.0 (R14) in the way that the SAVE command handles multiple variables as arguments.
When writing to an ASCII text file, SAVE will write the variables in alphabetical order regardless of the ordering of the variables in the command. In order to work around this issue, try renaming your variables to correspond to the alphabetical ordering that you wish them to appear in the file.
For example, you can use the following function in lieu of SAVE when using the -ascii flag:
function asciisave(varargin)
k = length(varargin);
% use savestring to capture the variables to be written
savestring = '';
% index through each variable argument and order alphabetically
for m=1:k-2
eval(['var' num2str(m) '= evalin(''base'',[varargin{m+1}]);']);
savestring = [savestring 'var' num2str(m) ' '];
end
% write to file
eval(['save ' varargin{1} ' ' savestring ' -ascii']);
For example, instead of saving variables to file as in the following code:
x=1;y=2;z=3;
save('test1.txt','z','y','x','-ascii');
use:
x=1;y=2;z=3;
asciisave('test1.txt','z','y','x','-ascii');
Note that this function has not officially been tested by MathWorks.