How to save array of structures in .mat file in Matlab? Is it possible?
p(1).x=0;
p(1).y=0;
p(2).x=1;
p(2).y=1;
save('matfilename','-struct','p');
% ??? Error using ==> save
% The argument to -STRUCT must be the name of a scalar structure variable.
You can use save without the -struct parameter:
>> p(1).x = 0;
>> p(1).y = 0;
>> p(2).x = 1;
>> p(2).y = 1;
>> save('myvars.mat', 'p');
>> clear p;
>> load('myvars.mat');
>> p(1)
ans =
x: 0
y: 0
>> p(2)
ans =
x: 1
y: 1
If you want want to store x and y as separate arrays (as -store would if p was a scalar struct) then you'll need to do it yourself (you can use the fieldnames function to collect the names of all fields in a struct).
Related
MATLAB stores variables along with anonymous functions. Here is an example of how this works from the documentation.
Variables in the Expression:
Function handles can store not only an expression, but also variables
that the expression requires for evaluation.
For example, create a function handle to an anonymous function that
requires coefficients a, b, and c.
a = 1.3;
b = .2;
c = 30;
parabola = #(x) a*x.^2 + b*x + c;
Because a, b, and c are available at the time you create parabola, the
function handle includes those values. The values persist within the
function handle even if you clear the variables:
clear a b c
x = 1;
y = parabola(x)
y =
31.5000
Supposedly, the values of a b and c are stored with the function even when it's saved and reloaded from a mat file. In practice, I've found that these values do not persist, especially if the code that originally created the function is edited.
Is there a way to define the function handle in terms of the numeric values of the variables? I would like something of the form
>> a = 1.3;
>> b = .2;
>> c = 30;
>> parabola = #(x) a*x.^2 + b*x + c
parabola = #(x) a*x.^2+b*x+c
>> parabola2 = forceEval(parabola)
parabola2 = #(x) 1.3*x.^2+.2x+30
EDIT: Perhaps my problem is with the file association, but when I edit the file that I originally defined the anonymous function in, I get an error that looks like:
Unable to find function #(ydata)nr/(na*dt)*normpdf(ydata,mu(j),s(j))./normpdf(ydata,mu_a(j),s_a(j)) within
C:...\mfilename.m. (where I've changed the name of my mfile to mfilename)
My usual solution to this kind of stuff has been to use func2str() to remove the file dependency, but this also strips out the workspace information including the parameter values. So I would like to force all the parameters to take on their numerical values in the function definition.
The values are stored in the function. As I've demonstrated in different answers before, you can check this with the functions command:
>> a = 1.3; b = .2; c = 30;
>> parabola = #(x) a*x.^2 + b*x + c;
>> x = 1;
>> y = parabola(x)
y =
31.5
>> clear a b c
>> y = parabola(x)
y =
31.5
>> fi = functions(parabola)
fi =
function: '#(x)a*x.^2+b*x+c'
type: 'anonymous'
file: ''
workspace: {[1x1 struct]}
>> fi.workspace{1}
ans =
a: 1.3
b: 0.2
c: 30
Even when you save the handle to disk:
>> save parabolaFun.mat parabola
>> clear parabola a b c
>> load parabolaFun.mat parabola
>> y = parabola(x)
y =
31.5
>> fi = functions(parabola)
fi =
function: '#(x)a*x.^2+b*x+c'
type: 'anonymous'
file: ''
workspace: {[1x1 struct]}
>> fi.workspace{1}
ans =
a: 1.3
b: 0.2
c: 30
And you can simplify the creation of a parabola handle like this:
function p = makeParabola(a,b,c)
p = #(x) a*x.^2 + b*x + c;
end
There are certain caveats:
You can save and load function handles in a MAT-file using the MATLABĀ® save and load functions. If you load a function handle that you saved in an earlier MATLAB session, the following conditions could cause unexpected behavior:
Any of the files that define the function have been moved, and thus no longer exist on the path stored in the handle.
You load the function handle into an environment different from that in which it was saved. For example, the source for the function either does not exist or is located in a different folder than on the system on which the handle was saved.
In both of these cases, the function handle is now invalid because it is no longer associated with any existing function code. Although the handle is invalid, MATLAB still performs the load successfully and without displaying a warning. Attempting to invoke the handle, however, results in an error.
Hence, if you create the handle from a file-backed function (not a script, that's OK), and then modify or delete the file, the handle will become invalid.
Anonymous functions capture the values of all variables involved in the expression. If you want to see the environment workspace captured, use functions as #chappjc showed in his answer.
Now you gotta be careful about the type of variables used in the anonymous function (think value-type vs. handle-type).
All native types (numerics, logicals, structs, cells, etc..) are captured by-value not by-reference. Example:
x = magic(4);
f = #() x; % captures matrix x
x(1) = 1 % modify x
xx = f() % change not reflected here
Compare that to using handle-class types (e.g containers.Map):
x = containers.Map('KeyType','char', 'ValueType','double');
f = #() x; % captures handle-class object x
x('1') = 1; % modify map
keys(x) % changed
keys(f()) % also changed!
f() == x % compare handle equality, evaluates to true
a = 1.3, b = 0.2, c = 30;
parabola = eval(['#(x) ', num2str(a), '*x^2 + ', num2str(b), '*x + ', num2str(c)]);
Define a syms vector
f = sym('f', [1 100]);
Define a syms variable x
syms x
The elements in vector f may be accessed and assigned, e.g.,
f(i) = x
Given any k, then how do I know if f(k) is assigned?
Short answer
Let k be the index of the entry of f to be inspected. Then
isAssigned = ~isempty(whos(char(f(k))));
is true (or 1) if the k-th entry of f has been assigned and false (or 0) otherwise.
Long answer
From the documentation (boldface added)
A = sym('a',[m,n]) creates an m-by-n symbolic matrix filled with automatically generated elements. The generated elements do not appear in the MATLAB workspace.
For example,
>> clear all
>> f = sym('f', [1 10])
>> f =
[ f1, f2, f3, f4, f5, f6, f7, f8, f9, f10]
>> whos
Name Size Bytes Class Attributes
f 1x10 112 sym
which indeed shows that f1, f2 etc don't appear in the workspace. However, if you then assign
>> syms x;
>> f(3) = x
f =
[ f1, f2, x, f4, f5, f6, f7, f8, f9, f10]
the variable x of course does appear in the workspace:
>> whos
Name Size Bytes Class Attributes
f 1x10 112 sym
x 1x1 112 sym
So, a way to check if a particular entry of f has been assigned is to check for its existence in the workspace using the functional form of whos. Compare
>> whos('f2') %// produces no output because no variable f2 exists in the workspace
and
>> whos('x') %// produces output because variable x exists in the workspace
Name Size Bytes Class Attributes
x 1x1 112 sym
Given the index k of the entry of f to be inspected, you can automatically generate the corresponding string ('f2' or 'x' in the above example) using char(f(k)):
>> k = 2;
>> char(f(k))
ans =
f2
>> k = 3;
>> char(f(k))
ans =
x
It only remains to assign the output of whos(char(f(k))) to a variable, which will be empty if f(k) has not been assigned, and non-empty if it has been assigned:
>> k = 2;
>> t = whos(char(f(k)))
t =
0x1 struct array with fields:
name
size
bytes
class
global
sparse
complex
nesting
persistent
>> k = 3;
>> t = whos(char(f(k)))
t =
name: 'x'
size: [1 1]
bytes: 112
class: 'sym'
global: 0
sparse: 0
complex: 0
nesting: [1x1 struct]
persistent: 0
Thus, applying ~isempty to this t produces true (1) if the k-th entry of f has been assigned and false (0) otherwise:
>> k = 2;
>> isAssigned = ~isempty(whos(char(f(k))))
isAssigned =
0
>> k = 3;
>> isAssigned = ~isempty(whos(char(f(k))))
isAssigned =
1
MATLAB stores variables along with anonymous functions. Here is an example of how this works from the documentation.
Variables in the Expression:
Function handles can store not only an expression, but also variables
that the expression requires for evaluation.
For example, create a function handle to an anonymous function that
requires coefficients a, b, and c.
a = 1.3;
b = .2;
c = 30;
parabola = #(x) a*x.^2 + b*x + c;
Because a, b, and c are available at the time you create parabola, the
function handle includes those values. The values persist within the
function handle even if you clear the variables:
clear a b c
x = 1;
y = parabola(x)
y =
31.5000
Supposedly, the values of a b and c are stored with the function even when it's saved and reloaded from a mat file. In practice, I've found that these values do not persist, especially if the code that originally created the function is edited.
Is there a way to define the function handle in terms of the numeric values of the variables? I would like something of the form
>> a = 1.3;
>> b = .2;
>> c = 30;
>> parabola = #(x) a*x.^2 + b*x + c
parabola = #(x) a*x.^2+b*x+c
>> parabola2 = forceEval(parabola)
parabola2 = #(x) 1.3*x.^2+.2x+30
EDIT: Perhaps my problem is with the file association, but when I edit the file that I originally defined the anonymous function in, I get an error that looks like:
Unable to find function #(ydata)nr/(na*dt)*normpdf(ydata,mu(j),s(j))./normpdf(ydata,mu_a(j),s_a(j)) within
C:...\mfilename.m. (where I've changed the name of my mfile to mfilename)
My usual solution to this kind of stuff has been to use func2str() to remove the file dependency, but this also strips out the workspace information including the parameter values. So I would like to force all the parameters to take on their numerical values in the function definition.
The values are stored in the function. As I've demonstrated in different answers before, you can check this with the functions command:
>> a = 1.3; b = .2; c = 30;
>> parabola = #(x) a*x.^2 + b*x + c;
>> x = 1;
>> y = parabola(x)
y =
31.5
>> clear a b c
>> y = parabola(x)
y =
31.5
>> fi = functions(parabola)
fi =
function: '#(x)a*x.^2+b*x+c'
type: 'anonymous'
file: ''
workspace: {[1x1 struct]}
>> fi.workspace{1}
ans =
a: 1.3
b: 0.2
c: 30
Even when you save the handle to disk:
>> save parabolaFun.mat parabola
>> clear parabola a b c
>> load parabolaFun.mat parabola
>> y = parabola(x)
y =
31.5
>> fi = functions(parabola)
fi =
function: '#(x)a*x.^2+b*x+c'
type: 'anonymous'
file: ''
workspace: {[1x1 struct]}
>> fi.workspace{1}
ans =
a: 1.3
b: 0.2
c: 30
And you can simplify the creation of a parabola handle like this:
function p = makeParabola(a,b,c)
p = #(x) a*x.^2 + b*x + c;
end
There are certain caveats:
You can save and load function handles in a MAT-file using the MATLABĀ® save and load functions. If you load a function handle that you saved in an earlier MATLAB session, the following conditions could cause unexpected behavior:
Any of the files that define the function have been moved, and thus no longer exist on the path stored in the handle.
You load the function handle into an environment different from that in which it was saved. For example, the source for the function either does not exist or is located in a different folder than on the system on which the handle was saved.
In both of these cases, the function handle is now invalid because it is no longer associated with any existing function code. Although the handle is invalid, MATLAB still performs the load successfully and without displaying a warning. Attempting to invoke the handle, however, results in an error.
Hence, if you create the handle from a file-backed function (not a script, that's OK), and then modify or delete the file, the handle will become invalid.
Anonymous functions capture the values of all variables involved in the expression. If you want to see the environment workspace captured, use functions as #chappjc showed in his answer.
Now you gotta be careful about the type of variables used in the anonymous function (think value-type vs. handle-type).
All native types (numerics, logicals, structs, cells, etc..) are captured by-value not by-reference. Example:
x = magic(4);
f = #() x; % captures matrix x
x(1) = 1 % modify x
xx = f() % change not reflected here
Compare that to using handle-class types (e.g containers.Map):
x = containers.Map('KeyType','char', 'ValueType','double');
f = #() x; % captures handle-class object x
x('1') = 1; % modify map
keys(x) % changed
keys(f()) % also changed!
f() == x % compare handle equality, evaluates to true
a = 1.3, b = 0.2, c = 30;
parabola = eval(['#(x) ', num2str(a), '*x^2 + ', num2str(b), '*x + ', num2str(c)]);
Let's say I want to store the function y(x) = x + 2 in a variable.
Is there any way to save y = x + 2, and access as y(x)? For example, y(2)?
An anonymous function is what you're looking for:
>> y = #(x) x+2;
>> y(2)
ans =
4
As an experiment (and because I'm generating anonymous functions off of user data) I ran the following MATLAB code:
h = #(x) x * x
h = #(x) x * x
h(3)
ans = 9
h = #(x) h(x) + 1
h = #(x)h(x)+1
h(3)
ans = 10
Basically, I made an anonymous function call itself. Instead of acting recursively, MATLAB remembered the old function definition. However, the workspace doesn't show it as one of the variables, and the handle doesn't seem to know it either.
Will the old function be stored behind the scenes as long as I keep the new one? Are there any "gotchas" with this kind of construction?
An anonymous function remembers the relevant part of the workspace at the time of definition, and makes a copy of it. Thus, if you include a variable in the definition of the anonymous function, and change that variable later, it will keep the old value inside the anonymous function.
>> a=1;
>> h=#(x)x+a %# define an anonymous function
h =
#(x)x+a
>> h(1)
ans =
2
>> a=2 %# change the variable
a =
2
>> h(1)
ans =
2 %# the anonymous function does not change
>> g = #()length(whos)
g =
#()length(whos)
>> g()
ans =
0 %# the workspace copy of the anonymous function is empty
>> g = #()length(whos)+a
g =
#()length(whos)+a
>> g()
ans =
3 %# now, there is something in the workspace (a is 2)
>> g = #()length(whos)+a*0
g =
#()length(whos)+a*0
>> g()
ans =
1 %# matlab doesn't care whether it is necessary to remember the variable
>>