In my program, I have a large (for example, 100x100) array of structures, each of which has a sufficient amount of data (for example, 1000 numbers and some other fields). For example:
for x = 100 : -1 : 1 for y = 100 : -1 : 1 database(y,x).data = rand(30); database(y,x).name = sprintf('my %d %d', x, y); end end
I would like to do the calculation of 10-20 lines of code with my data; eg:
for x = 10 : 90 for y = 10 : 90 for dx = -9 : 9 for dy = -9 : 9 result = result + database(y + dy, x + dx).data(1, 1); result = result + 2 * database(y + dy, x + dx).data(1, 2) * database(y + dy, x + dx).data(2, 2); ... % more stuff here end end end end
My code refers to the current database item as database(y + dy, x + dx) . To make it shorter, I give it a name (C ++ would call it a link):
temp = database(y + dy, x + dx); result = result + temp.data(1, 1); result = result + 2 * temp.data(1, 2) * temp.data(2, 2);
This makes my code much shorter and clearer. However, this is also much slower, and profiling shows that assigning temp = ... takes 70% of the execution time.
So my assumption is that Matlab is copying the contents of a fairly large database item, eating my time. I think Matlab should be smart enough to do copy-on-write, that is, copy material only when it is changed later. However, this is not what happens in my case - my code only reads from the database and does not change it.
So, how can I make an effective read-only link for a structure?