Matrix or vector operation faster?

2 views (last 30 days)
Simon Schiele
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
dNNdt = dNNdt(:); %convert to vector for ode45
function odefun2 %converting each matrix to a vector before calculations
dNNdt = ...
reshape(G1_3D_pos(1:end-1,:,:),[],1,1).*reshape(nn_3D_atX1Borders_pos(1:end-1,:,:),[],1,1)) + ...
%solve ode using either odefun1 or odefun2
[y,t] = ode45(@odefun,[0 1],y0)

Accepted Answer

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?
produces the same result as:
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.

More Answers (0)




Community Treasure Hunt

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

Start Hunting!