Loopin through all the structures in a workspace [duplicate] - matlab

I have 40 structures in my Workspace. I Need to write a script to calculate the directional derivatives of all the elements. Here is the code :
[dx,dy] = gradient(Structure_element_1.value);
dxlb = min(min(dx));
dxub = max(max(dx));
dylb = min(min(dy));
dyub = max(max(dy));
[ddx,ddy] = gradient(gradient(Structure_element_1.value));
ddxlb = min(min(ddx));
ddxub = max(max(ddx));
ddylb = min(min(ddy));
ddyub = max(max(ddy));
This is the code for one element. I Need to find out the same for all the 40 elements and then use it later. Can anyone help with this.

To answer your literal question, you should store the variables in a structure array or at least a cell array. If all of your structures have the same fields, you can access all of them by indexing a single array variable, say Structure_element:
for i = 1:numel(Structure_element)
field = Structure_element(i).value
% compute gradients of field
end
Now to address the issue of the actual gradient computation. The gradient function computes an approximation for , where is your matrix of data. Normally, a MATLAB function is aware of how many output arguments are requested. When you call gradient(gradient(F)), the outer gradient is called on the first output of the inner gradient call. This means that you are currently getting an approximation for .
I suspect that you are really trying to get . To do this, you have to get both outputs from the inner call to gradient, pass them separately to the
outer call, and choose the correct output:
[dx,dy] = gradient(F);
[ddx, ~] = gradient(dx);
[~, ddy] = gradient(dy);
Note the separated calls. The tilde was introduced as a way to ignore function arguments in MATLAB Release 2009b. If you have an older version, just use an actual variable named junk or something like that.

Related

Structure variable as input in MATLAB function using VARARGIN

I wrote a main function in Matlab that calls other functions, each of which produces plots in a new figure. Though each function produces different plots (different colors, number of subplots, and so on) they all share some features (font, fontsize, Linewidth etc.).
In order to make it easier to modify the aforementioned shared parameter for all the MATLAB figures, I have defined in the preamble of the main function a structure variable as follows:
var.font = 'Arial Unicode MS';
var.fontsize = 13;
var.interpreter = 'none' ;
and so on for the other fields. When I call the function in this way (providing the structure as input):
function plot1( var , ... )
fig = gcf
fig.Position(3) = var.Position3
fig.Position(4) = var.Position4
end
everything works fine and the functions apply the feature to each figure. But if I try to provide a variable number of input to the functions using varargin, in this way
function plot1( varargin )
fig = gcf;
temp = varargin(1);
fig.Position(3) = temp.Position3;
fig.Position(4) = temp.Position4;
end
The following error message is prompted "Struct contents reference from a non-struct array object."
You're indexing the cell array incorrectly (this is easily done).
Round parentheses ( ) give you a cell output when indexing a cell array - i.e. your temp is a 1x1 cell with the struct inside it.
You need curly braces { } to extract the contents of a cell array.
Fix: use curly braces:
temp = varargin{1};
I sometimes think of cell arrays as a group of boxes, since each element (or "box" in this analogy) can basically contain anything. To extract a subset of boxes, use round parentheses. To extract the contents of the boxes, use braces. This analogy extends also to tables, where the notation is consistent.
Here's some docs on indexing cell arrays, where the difference is described in more detail:
https://uk.mathworks.com/help/matlab/matlab_prog/access-data-in-a-cell-array.html

Directional Derivatives of a Matrix

I have 40 structures in my Workspace. I Need to write a script to calculate the directional derivatives of all the elements. Here is the code :
[dx,dy] = gradient(Structure_element_1.value);
dxlb = min(min(dx));
dxub = max(max(dx));
dylb = min(min(dy));
dyub = max(max(dy));
[ddx,ddy] = gradient(gradient(Structure_element_1.value));
ddxlb = min(min(ddx));
ddxub = max(max(ddx));
ddylb = min(min(ddy));
ddyub = max(max(ddy));
This is the code for one element. I Need to find out the same for all the 40 elements and then use it later. Can anyone help with this.
To answer your literal question, you should store the variables in a structure array or at least a cell array. If all of your structures have the same fields, you can access all of them by indexing a single array variable, say Structure_element:
for i = 1:numel(Structure_element)
field = Structure_element(i).value
% compute gradients of field
end
Now to address the issue of the actual gradient computation. The gradient function computes an approximation for , where is your matrix of data. Normally, a MATLAB function is aware of how many output arguments are requested. When you call gradient(gradient(F)), the outer gradient is called on the first output of the inner gradient call. This means that you are currently getting an approximation for .
I suspect that you are really trying to get . To do this, you have to get both outputs from the inner call to gradient, pass them separately to the
outer call, and choose the correct output:
[dx,dy] = gradient(F);
[ddx, ~] = gradient(dx);
[~, ddy] = gradient(dy);
Note the separated calls. The tilde was introduced as a way to ignore function arguments in MATLAB Release 2009b. If you have an older version, just use an actual variable named junk or something like that.

Add a number to a struct field [duplicate]

Suppose I have a struct array arr, where each element has a bunch of fields, including one called val. I'd like to increment each element's val field by some constant amount, like so:
for i = 1:length(arr)
arr(i).val = arr(i).val + 3;
end
This obviously works, but I feel there should be a way to do this in just one line of code (and no for loop). The best I've come up with is two lines and requires a temp variable:
newVals = num2cell([arr.val] + 3);
[arr.val] = deal(newVals{:});
Any ideas? Thanks.
Just a note, the deal isn't necessary there:
[arr.val] = newVals{:}; % achieves the same as deal(newVals{:})
The only other way I know how to do this (without the foor loop) is using arrayfun to iterate over each struct in the array:
% make a struct array
arr = [ struct('val',0,'id',1), struct('val',0,'id',2), struct('val',0,'id',3) ]
% some attempts
[arr.val]=arr.val; % fine
[arr.val]=arr.val+3; % NOT fine :(
% works !
arr2 = arrayfun(#(s) setfield(s,'val',s.val+3),arr)
That last command loops over each struct in arr and returns a new one where s.val has been set to s.val=3.
I think this is actually less efficient than your previous two-liner and the for loop though, because it returns a copy of arr as opposed to operating in-place.
(It's a shame Matlab doesn't support layered indexing like [arr.val]=num2cell([arr.val]+3){:}).
I like Carl's and mathematical.coffee's original ideas.
I have multiple similar lines to express, so for concision of my mainline code,
I went ahead and made the generic subfunction
function varargout = clist(in)
varargout = {in{:}};
end
then I could express each such line in a fairly readable way
[arr.var] = clist(num2cell([arr.var]+3));
[arr.var2] = clist(num2cell([arr2.var]/5+33));
Are all the fields in that struct scalar, or the same size? If so, the idiomatic Matlab way to do this is to rearrange your struct to be a scalar struct with arrays in each of its fields, instead of an array of structs with scalar values in the fields. Then you can do vectorized operations on the fields, like arr.val = arr.val + 3;. See if you can rearrange your data. Doing it this way is much more efficient in both time and memory; that's probably why Matlab doesn't provide convenient syntax for operating over fields of arrays of structs.
if the struct array you are trying to set is a set of graphics objects (line handles, figure handles, axes handles, etc), then you need to use the function set:
x = (1:10)';
Y = rand(10,5);
l = plot(x,Y,'-k'); % returns an array of line handles in l
set(l,'Color','r'); % sets the property 'Color' for all the five lines in l

Converting mixed empty/non-empty cells into a numeric matrix

I am working on a code to extract my AR(1)-GARCH(1) parameter, which I estimated using an AR(1)-GJR(1,1) model to individual matrices so that I can use them as variables in my calculations. As I have 16 time series variables, I combine the code with a loop in the following way:
for i=1:nIndices
AA_ARCH(:,i) = cell2mat(fit{i}.Variance.ARCH)';
end;
My problem is that for some variables is are no for AA_ARCH(:,i) the dimension is lower than nIndices. Naturally, when I try to export the estimates in the loop which specified the dimension of (:,i) and nIndices matlab reports a dimension mismatch. I would like to tell Matlab to replace the NaN with 0 instead of leaving the spot empty so that it is able to produce a (1,nIndices) matrix from AA_ARCH.
I thought of something like the this:
fit{i}.Variance.Leverage(isnan(fit{i}.Variance.Leverage))=0
but I wasn't able to combine this part with the previous code.
I would be very happy about any hints!
Best, Carolin
UPDATE:
Here is a fully a runnable version of my code which produces my problem. Notice that the code produces a dimension mismatch error because there is no ARCH and GARCH estimate in the fit.gjr(1,1) for time series 1. For these missing values I would like to have 0 as a placeholder in the extracted matrix.
returns = randn(2,750)';
T = size(returns,1);
nIndices = 2;
model = arima('AR', NaN, 'Variance', gjr(1,1));
residuals = NaN(T, nIndices);
variances = NaN(T, nIndices);
fit = cell(nIndices,1);
options = optimset('fmincon');
options = optimset(options, 'Display' , 'off', 'Diagnostics', 'off', ...
'Algorithm', 'sqp', 'TolCon' , 1e-7);
for i = 1:nIndices
fit{i} = estimate(model, returns(:,i), 'print', false, 'options', options);
[residuals(:,i), variances(:,i)] = infer(fit{i}, returns(:,i));
end
for i=1:nIndices
AA_beta(:,i) = cell2mat(fit{i}.AR)';
AA_GARCH(:,i) = cell2mat(fit{i}.Variance.GARCH)';
AA_ARCH(:,i) = cell2mat(fit{i}.Variance.ARCH)';
AA_Leverage(:,i) = cell2mat(fit{i}.Variance.Leverage)';
end;
I have some general things to say about the code, but first a solution to your problem:
You can put a simple if/else structure in your loop to handle the case of an empty array:
for ind1=1:nIndices
AA_beta(:,ind1) = cell2mat(fit{ind1}.AR)'; %//'
%// GARCH
if isempty(cell2mat(fit{ind1}.Variance.GARCH)') %//'
AA_GARCH(1,ind1) = 0;
else
AA_GARCH(:,ind1) = cell2mat(fit{ind1}.Variance.GARCH)'; %//'
end
%// ARCH (same exact code, should probably be exported to a function)
if isempty(cell2mat(fit{ind1}.Variance.ARCH)') %//'
AA_ARCH(1,ind1) = 0;
else
AA_ARCH(:,ind1) = cell2mat(fit{ind1}.Variance.ARCH)'; %//'
end
AA_Leverage(:,ind1) = cell2mat(fit{ind1}.Variance.Leverage)'; %//'
end;
Side note: I initially tried something like this: soz = #(A)isempty(A)*0+~isempty(A)*A; as an inline replacement for the if/else, but it turns out that MATLAB doesn't handle [] + 0 the way I wanted (it results in [] instead of 0; unlike other languages like JS).
As for the other things I have to say:
I am a firm supporter of the notion that one shouldn't use i,j as loop indices, as this may cause compatibility problems in some cases where complex numbers are involved (e.g. if you loop index is i then 1*i now refers to the loop index instead of to the square root of -1).
Part of your problem was that the arrays you were writing into weren't preallocated - which also means the correct datatype was unknown to MATLAB at the time of their creation. Besides the obvious performance hit this entails, it could also result in errors like the one you encountered here. If, for example, you used cells for AA_beta etc. then they could contain empty values, which you could later replace with whichever placeholder your heart desired using a combination of cellfun and isempty. Bottom line: lint (aka the colorful square on the top right of the editor window) is your friend - don't ignore it :)

how to apply iddata into calculation?

I am trying to figure out how to combine the input and output data into the ARX model and then apply it into the BIC (Bayesian Information Criterion) formula. Below is the code that I am currently working on:
for i=1:30; %% Set Model Order
data=iddata(output,input,1);
model = arx(data,[8 9 i]);
yp = predict(model,data);
ye = regress(data,yp{1,1}(1:4018,1));
M(i) = var(yp);
BIC(i)=(N+i*(log(N)-1))/(N-i)*log(M(i));
end
But it does not work. It keeps on giving me an error that's something like below:
"The syntax "Data{...}" is not supported. Use the "getexp" command to
extract individual experiments from an IDDATA object."
I did not understand what does that mean. Can someone explain it to me and where do I do wrong on my piece of code?
Update:
I tried to do it something like below, so far, there is no error. But then the graph for this BIC will be always straight line. Is something wrong with my regression part? how should I do for the regression?
N=length(rainfall_model);
for i=1:20; % Set Model Order
data=iddata(rainfall_model,tmax_model,1);
%d1 = getexp(data,1);
model = arx(data,[50 9 i]);
yp=predict(model,data);
y = yp.y ;
d1 = data.y ;
ye = (d1).^2 - (y).^2;
M(i)= mse(ye);
BIC(i)=(N+i*(log(N)-1))/(N-i)*log(M(i));
end
In your code example, yp returned from the 'predict' command is an iddata object and the cell notation '{...}' cannot be used with it. If you want to do regression, you have to extract the input (yp.u) or the output (yp.y) data from it.
Also, the command 'regress' does not work with idddata objects, since it is not a system identification toolbox function. Again you have to extract input or output data from the 'data' and 'yp' variables before calling it.
Update: To see what's in the iddata objects (data and yp), do
get(data)
get(yp)
You would see that you can extract the output data in two equivalent ways:
yp.y
yp.OutputData
Similarly, for the input data.