-4

This is a Matlab function and I'm trying to rewrite it in C. The input x1 is a 3 dimensional array and hx,hy,hz are just numbers. The problem I am having is understanding exactly how the elements of the 3D array are assigned. How does this last line work?

function Ax = D_XX_YY_ZZ(x1,hx,hy,hz)

[mx1, my1, mz1]=size(x1);

Ax = (x1(1:mx1-2,2:my1-1,2:mz1-1)+ ...
 +x1(3:mx1,2:my1-1,2:mz1-1) )/(hx^2) + ...
 (x1(2:mx1-1,1:my1-2,2:mz1-1)+ ...
 +x1(2:mx1-1,3:my1,2:mz1-1) )/(hy^2) + ...
 (x1(2:mx1-1,2:my1-1,1:mz1-2)+ ...
 +x1(2:mx1-1,2:my1-1,3:mz1) )/(hz^2) ;
user906357
  • 4,575
  • 7
  • 28
  • 38
  • 1
    doesn answer the question, but would be useful to generate the C code for the function with [Matlab Coder](http://it.mathworks.com/videos/generating-c-code-from-matlab-code-68964.html) and look into the generated code. – Vahid Jul 06 '16 at 13:39

1 Answers1

1

Lets say you have a matlab matrix A.

 A(1:end) = 3;

This sets all of the elements from A(1) to A(end) to 3. Likewise, if you have

 B = A(5:8)

Then B will contain elements A(5), A(6), A(7), and A(8).

So the code if the code was

 Ax = x1(3:mx1,2:my1-1,2:mz1-1) )/(hx^2)

It can be written as:

 for (int i = 3; i <= mx1; i++)
     for(int j = 2; j <= my1-1; j++)
         for(int k = 2; k <= mz1-1; k++)
              Ax[i-3][j-2][k-2] = pow(x1[j][i][k], 2);

If I remember correctly matlab is column first and c is row first, which is why it is x1[j][i]... not x1[i][j], but I may have remembered wrong so you may wish to confirm that.

Also note that this affects how the arrays are stored in memory, and thus you should account for this if you care about your code being efficient. This wikipedia article explains how in c an array will be stored row major, and in matlab column major. Basically it's faster to access elements that are closer to eachother in memory because you have to write to cache less.

More on this: What is "cache-friendly" code?.

Community
  • 1
  • 1
Shawn
  • 409
  • 3
  • 12