I’m trying to optimize this piece of code. This is the simplified version (not the actual code).
for i = 1:1000000
a(i).x = a(i).x+1;
a(i).y = a(i).y*2;
a(i).f = i:i+128;
end
I know if I deference a(i) once it’s going to be faster. Like the following:
for i = 1:1000000
b = a(i);
b.x = b.x+1;
b.y = b.y*2;
b.f = i:i+128;
a(i) = b;
end
Here I copy a(i) to b and back to a(i) at the end. Is it possible to just define a pointer to a(i)? Something similar to C++.
MATLAB has
handledata types which are similar to references in other languages, but I think that is not appropriate here.The main optimization I would suggest here is to use a structure of large arrays, rather than a large array of structures. In other words, your code might look more like this:
This approach is usually significantly faster and more memory efficient.