array of structures with scalar fields vs. single structure with vector fields

array of structures with scalar fields vs. single structure with vector fields

Post by Martin Sch » Fri, 03 Apr 2009 02:45:18


I am running semiconductor simulations, where semiconductor equations are discretized on a grid. Multiple material parameters are defined at each gridpoint. Ideally I would like to have an array of structures - one element for each gridpoint - containing these material parameters as scalar fields.

I would like an array of structures, because oftentimes I need to do calculations using only a subset of the gridpoints. Using an array of structures, lets call it 's', the function call would simply look like:

result = myFunction(s(10:20));

This is very intuitive to me. Alternatively I could define a structure where the fields are vectors which contain the material parameters at each gridpoint location. However, function calls may then become messy:

result = myFunction(s.A(10:20),s.B(10:20),s.C(10:20),...);

However, I have found that the former approach is much slower. Here is some example code:

function [] = speedTest()
len = 2e4;
m1(len).x = [];
m2.x = zeros(len,1);
for ii=1:len,
x = rand;
m1(ii).x = x;
m2.x(ii) = x;
end
tic
r1 = method1(m1(1:round(len/2)));
toc
tic
r2 = method2(m2.x(1:round(len/2)));
toc

function [result] = method1(m1)
result = exp([m1.x]).*[m1.x];

function [result] = method2(x)
result = exp(x).*x;

Method 1 runs much slower than method 2. This means I either need to write either slower code or code that is more difficult to understand. Is there any way to get the best of both worlds?
 
 
 

array of structures with scalar fields vs. single structure with vector fields

Post by Bruno Luon » Fri, 03 Apr 2009 03:20:18


This would be a dream!!!

Bruno