# Matrix or vector operation faster?

2 views (last 30 days)
Simon Schiele on 29 Apr 2022
Answered: Jan on 29 Apr 2022
I am solving a set of 3e5 differential equation using ode45.
My code is written such that the equations are in a 3D matrix because its better to read. Would you expect odefun1 or odefun2 to work faster?
Initially, I used odefun2 but then thought it looked ugly and figured I could just convert everything to a vector (as ode45 needs it) in the end. My code is slower now, but I made heaps of other changes so I am not sure if the choice of odefun1/2 contributes.
Short code snippet:
function odefun1 %writen as 3D matrix
dNNdt = ...
delta_xx3.*delta_xx2.*(... %both deltas are matrices
G1_3D_pos(2:end,:,:).*nn_3D_atX1Borders_pos(2:end,:,:)
dNNdt = dNNdt(:); %convert to vector for ode45
end
function odefun2 %converting each matrix to a vector before calculations
dNNdt = ...
delta_xx3(:).*delta_xx2(:).*(...
reshape(G1_3D_pos(1:end-1,:,:),[],1,1).*reshape(nn_3D_atX1Borders_pos(1:end-1,:,:),[],1,1)) + ...
end
%solve ode using either odefun1 or odefun2
[y,t] = ode45(@odefun,[0 1],y0)

Jan on 29 Apr 2022
The number of multiplications is the same in both versions, as far as I can see. So I'd expect both to need almost the same time. But other aspects are more interesting:
Why is the index 2:end in one case and 1:end-1 in the other?
Where do the variables come from? Are they persistently stored, global or parameters?
Creating the subarrays G1_3D_pos(2:end,:,:) and nn_3D_atX1Borders_pos(2:end,:,:) is expensive. Can this be done once externally?
This:
reshape(G1_3D_pos(1:end-1,:,:),[],1,1)
produces the same result as:
reshape(G1_3D_pos(1:end-1,:,:),[],1)
because trailing dimensions of length 1 are ignored in Matlab (except for column vectors, which are [M x 1].
Why do you ask for the speed? Simply try it.

R2021b

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!