## MATLAB: Usage of structure as input of a function. Is it efficient

functionsMATLABmatlab coderoptimizationstructures

Hello Mathworks community,

I have a general questioning about the efficiency / relevance of using structures as function inputs. I’ll try to be clear…

I’m working on a code that has around 300 variables. I find very convenient to gather / sort these variables as fields of a few (~5) structures to sort them by “type”. That clears my workspace and allow me to make shorter function calls. For example, I have a structure Model that contains fields .param1 .param2 … param40 (all different, can be scalars, small vectors or small 3D matrices).

So, when I want to make some computation, I just do :

`[output] = some_function(Model, other_input) ;`

Furthermore, I use in my code a lot of functions / sub-functions / sub-sub-functions… I know that this might not be the most relevant in MatLab, but I think I have a good reason to do so. First that simplifies the structure of my code since I have a lot of sequential actions, so having small divided tasks is way more easy to manage. And secondly I intend to translate the code in C using MatLab Coder to run on an embedded platform.

That scheme was fine for me, until I started working on optimization / computing time and realized that there was a big difference between the 2 solutions below:

`function [output] = some_function(Model, other_input)% [...]`

% Solution 1

% (tic)

% (for i = 1:1e6)

output = some_sub_function(Model.param1, Model.param2, Model.param3, other_input) ;% (end)

% (toc) ==> ~4 seconds

% Solution 2

P1 = Model.param1 ;P2 = Model.param2 ;P3 = Model.param3 ;% (tic)% (for i = 1:1e6) output = some_sub_function(P1, P2, P3, other_input) ;% (end)% (toc) ==> ~0.4 seconds, 10 times faster !

% [...]end

Since computing time is critical for my work, I start to doubt about the choices I made. The thing is that if I stop using structures, I’ll have gigantic function calls to write. And if I stop using functions, I’ll have a gigantic code to naviguate into…

I’ve struggled to find ressources online about that matter (maybe I didn’t find the right keywords), so I am curious about advices or feedback you could have ?

Thanks !

## Best Answer