How to make a link to a structure in Matlab?

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?

+7
performance reference matlab
source share
1 answer

Well, certain copying happens when you do:

 temp = database(y + dy, x + dx) 

This can be reduced, possibly using:

 temp = database(y + dy, x + dx).data 

But obviously, this will only work if you are interested in the data in this part of the code.

Having said that, I'm not sure that you can get around this without using inconvenient methods to structure your data. First of all, you can compare your code after replacing all temp with database(y + dy, x + dx) to ensure that avoiding copying really helps. If so, you can try feeding the database(y + dy, x + dx) subfunction, since the variables in the subfunction are usually used with read access, if that’s enough. However, I'm not sure if this also applies to parts of variables.

If none of the questions above help, consider one of the oldest tips in the book:

For efficient calculations on large chunks of data, consider using matrices.

+1
source share

All Articles