how can I vectorize my code when multiple variables are present
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hi All,
I'm trying to figure out how to vectorize my code when multiple variables are present. The following is the toy model with odes for 2 variables (Please note the code may not make much sense, in my real system variables w and u are coupled. Also, in the actual system the number of variables in the model is uder-defined. For this reason, I am looping through the variables in the for-loop).
global mat1 mat2 k nvar var npts
k = 2;
nvar =2;
var = ["w", "x"];
npts=10;
mat1=[
1 -2 1 0 0 0 0 0 0 0;
0 1 -2 1 0 0 0 0 0 0;
0 0 1 -2 1 0 0 0 0 0;
0 0 0 1 -2 1 0 0 0 0;
0 0 0 0 1 -2 1 0 0 0;
0 0 0 0 0 1 -2 1 0 0;
0 0 0 0 0 0 1 -2 1 0;
0 0 0 0 0 0 0 1 -2 1;
];
mat2 = [
1 -1 0 0 0 0 0 0 0 0;
0 1 -1 0 0 0 0 0 0 0;
0 0 1 -1 0 0 0 0 0 0;
0 0 0 1 -1 0 0 0 0 0;
0 0 0 0 1 -1 0 0 0 0;
0 0 0 0 0 1 -1 0 0 0;
0 0 0 0 0 0 1 -1 0 0;
0 0 0 0 0 0 0 1 -1 0;
];
w0 = [2 0 0 0 0 0 0 0 0 0]';
x0 = [1 0 0 0 0 0 0 0 0 0]';
z0 = [w0; x0];
tspan = 0:0.01:0.5;
f0 = fun(0, z0);
joptions = struct('diffvar', 2, 'vectvars', 2, 'thresh', 1e-8, 'fac', []);
J = odenumjac(@fun,{0 z0}, f0, joptions);
sparsity_pattern = sparse(J~=0.);
options = odeset('Stats', 'on', 'Vectorized', 'on'); %, 'JPattern', sparsity_pattern);
ttic = tic();
[t, sol] = ode15s(@(t,z) fun(t,z), tspan , z0, options);
ttoc = toc(ttic)
fprintf('runtime %f seconds ...\n', ttoc)
plot(t, sol)
function Zstruct = get_Zstruct(z)
global nvar var npts
temp = reshape(z, npts, []);
for i = 1:nvar
Zstruct.(var(i)) = temp(:,i);
end
end
function dz = fun(t,z)
global nvar var mat1 mat2
fprintf('size of z %d %d...\n', size(z))
dz = zeros(size(z), 'like', z);
Zstruct = get_Zstruct(z);
F =[];
for i = 1:nvar
x = Zstruct.(var(i));
f = zeros(size(x), 'like', x);
f(1,:) = 0;
f(2:9,:) = mat1*x + mat2*x;
f(10,:) = 2*(x(end-1) - x(end));
end
F(:,:) = vertcat(F,f);
end
I tried to check the size of z and it inconsistent for different function calls.
size of z 20 1...
size of z 20 20...
size of z 20 1...
size of z 20 1...
:
size of z 20 1...
size of z 20 1...
size of z 20 1...
size of z 20 20...
I'm sure the mistake is in the function Zstruct = get_Zstruct(z). I'm not sure how to vectorize here. Could someone please help me with this?
3 comentarios
Walter Roberson
el 23 de Feb. de 2021
for i = 1:nvar
Zstruct.(var(i)) = temp(:,i);
end
cell2struct() instead of the loop.
Respuestas (1)
darova
el 22 de Feb. de 2021
Try to remove parenthesis
1 comentario
Deepa Maheshvare
el 23 de Feb. de 2021
Editada: Deepa Maheshvare
el 23 de Feb. de 2021
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!