how can I vectorize my code when multiple variables are present
显示 更早的评论
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 个评论
Deepa Maheshvare
2021-2-22
Walter Roberson
2021-2-23
for i = 1:nvar
Zstruct.(var(i)) = temp(:,i);
end
cell2struct() instead of the loop.
Deepa Maheshvare
2021-2-23
编辑:Deepa Maheshvare
2021-2-23
回答(1 个)
darova
2021-2-22
0 个投票
Try to remove parenthesis

1 个评论
Deepa Maheshvare
2021-2-23
编辑:Deepa Maheshvare
2021-2-23
类别
在 帮助中心 和 File Exchange 中查找有关 Programming 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!