Thursday, September 11, 2008

Save workspace variables to disk

save -
Save workspace variables to disk

Graphical Interface

As an alternative to the save function, select Save Workspace As from the File menu in the MATLAB® desktop, or use the Workspace browser.

Syntax

save
save filename
save filename content
save filename options
save filename content options
save('filename', 'var1', 'var2', ...)


Examples

Example 1
Save all variables from the workspace in binary MAT-file test.mat:
save test.mat
Example 2
Save variables p and q in binary MAT-file test.mat.
In this example, the file name is stored in a variable, savefile. You must call save using the function syntax of the command if you intend to reference the file name through a variable.
savefile = 'test.mat';
p = rand(1, 10);
q = ones(10);
save(savefile, 'p', 'q')
Example 3
Save the variables vol and temp in ASCII format to a file named june10:
save('d:\mymfiles\june10','vol','temp','-ASCII')
Example 4
Save the fields of structure s1 as individual variables rather than as an entire structure.
s1.a = 12.7; s1.b = {'abc', [4 5; 6 7]}; s1.c = 'Hello!';
save newstruct.mat -struct s1;
clear
Check what was saved to newstruct.mat:
whos -file newstruct.mat
Name Size Bytes Class

a 1x1 8 double array
b 1x2 158 cell array
c 1x6 12 char array

Grand total is 16 elements using 178 bytes
Read only the b field into the MATLAB workspace.
str = load('newstruct.mat', 'b')
str =
b: {'abc' [2x2 double]}
Example 5
Using regular expressions, save in MAT-file mydata.mat those variables with names that begin with Mon, Tue, or Wed:
save('mydata', '-regexp', '^Mon|^Tue|^Wed');
Here is another way of doing the same thing. In this case, there are three separate expression arguments:
save('mydata', '-regexp', '^Mon', '^Tue', '^Wed');
Example 6
Save a 3000-by-3000 matrix uncompressed to file c1.mat, and compressed to file c2.mat. The compressed file uses about one quarter the disk space required to store the uncompressed data:
x = ones(3000);
y = uint32(rand(3000) * 100);

save -v6 c1 x y % Save without compression
save -v7 c2 x y % Save with compression

d1 = dir('c1.mat');
d2 = dir('c2.mat');

d1.bytes
ans =
45000240 % Size of the uncompressed data in bytes.
d2.bytes
ans =
11985283 % Size of the compressed data in bytes.

d2.bytes/d1.bytes
ans =
0.2663 % Ratio of compressed to uncompressed

No comments: