I have a question regarding the timing when accessing / reassigning variables either from a matlab struct or a matlab variable (any array):
Imagine the scenario that you have one function that creates ten variables (arrays of different dimensions and sizes). This function is getting called within another function that will need these variables produced.
Now, because getting ten variables from a function looks messy, I thought about storing these ten variables in a struct instead, and change my initial function so that it outputs only one struct (with ten fields) instead of ten variables.
Because timing is crucial for me (it's code for an EEG experiment), I wanted to make sure, that the struct approach is not slower, so I wrote the following test function.
function test_timingStructs
%% define struct
strct.a=1; strct.b=2; strct.c=3;
%% define "loose" variables
a = 1; b = 2; c = 3;
%% How many runs?
runs = 1000;
%% time access to struct
x = []; % empty variable
tic
for i=1:runs
x = strct.a; x = strct.b; x = strct.c;
end
t_struct = toc;
%% time access to "loose variables"
x = []; % empty variable
tic
for i=1:runs
x = a; x = b; x = c;
end
t_loose = toc;
%% Plot results
close all; figure;
bar(cat(2,t_struct,t_loose));
set(gca,'xticklabel', {'struct', 'loose variable'})
xlabel('variable type accessed', 'fontsize', 12)
ylabel(sprintf('time (ms) needed for %d accesses to 3 different variables', runs), 'fontsize', 12)
title('Access timing: struct vs "loose" variables', 'fontsize', 15)
end
According to the results, accessing a structure to get the values of a field is considerably slower than just accessing a variable. Can I make this assumption based on the test that I have done?
Is there another way to neatly "package" the ten variables without losing time when I want to access them?