Docsity

MATLAB, C, C++, and Java for Scientific Computing: Levitt's Puzzle Problem - Prof. Joh Cal, Study notes of Computer Science

Toggle sidebar
bg1
COMP 116
3 Dec 2006
MATLAB vs C, C++, or Java
MATLAB is interpreted, C and Java are compiled.
MATLAB has vectors, arrays, matrices, strings, and complex numbers as first-class
types, and has a huge set of functions that operate on them. C and Java has only doubles,
integers, characters and arrays. All variables must be declared before using, so that the
compiler can make space for them.
Certain symbols are different in C/C++/Java: “!” (called “bang”) for not, “| |” and “&&”
for logical OR and AND. (The “|” and “&” operators are used for bitwise OR and AND,
so should be avoided in C.)
Syntax of statements differs in C and MATLAB. Some examples:
o“for (i = 1; i <= 10; i++) { … }” instead of “for i=1:10 … end”
oTwo whiles: “while (condition) {…}” or “do { … } while (condition)”
oSemicolons are needed after every statement except those that precede a }.
oComments are indicated by “/* …C… */” and “// … C++/Java”
C programs start with main() and usually have several functions in one file. Java/C++
have one “class” per file, which is a data structure plus all the associated functions, some
of which are declared to be accessible from outside the file and others are private.
MATLAB uses file names to name functions. (Actually, you can have helper functions
inside a single file, too.)
MATLAB and C are procedural languages, emphasizing the function/subroutine. C++
and Java are “object oriented,” which emphasize the abstract data type and encourage
code re-use through inheritance and library building.
MATLAB and Java check types while the program is running. C and C++ check types at
compilation time, which means that the program is faster.
C and C++ rely on pointers, which indicate variables by their location in memory and
leave it to the programmer to interpret what type of value is there. Java uses references,
which always know the type of what they are pointing to.
MATLAB shows its Fortran roots in column-major storage order, use of global variables,
lack of pointers or references, etc.
In C and C++ you must manage the use of memory. Java & MATLAB do garbage
collection to clean up unused memory for you.
The C/C++/Java languages and some libraries are standardized by international
committees. Thus, many companies produce different development environments, with
different libraries, compilers, debuggers, and editors, for C/C++/Java.
MATLAB comes only from Mathworks, although R and Opal are “knock-offs.”
http://www.cprogramming.com/tutorial.html
http://java.sun.com/docs/books/tutorial/
http://www.physics.drexel.edu/courses/Comp_Phys/General/C_basics/c_tutorial.html
pf3
pf4

Partial preview of the text

Download MATLAB, C, C++, and Java for Scientific Computing: Levitt's Puzzle Problem - Prof. Joh Cal and more Study notes Computer Science in PDF only on Docsity!

3 Dec 2006

MATLAB vs C, C++, or Java

 MATLAB is interpreted, C and Java are compiled.  MATLAB has vectors, arrays, matrices, strings, and complex numbers as first-class types, and has a huge set of functions that operate on them. C and Java has only doubles, integers, characters and arrays. All variables must be declared before using, so that the compiler can make space for them.  Certain symbols are different in C/C++/Java: “!” (called “bang”) for not, “| |” and “&&” for logical OR and AND. (The “|” and “&” operators are used for bitwise OR and AND, so should be avoided in C.)  Syntax of statements differs in C and MATLAB. Some examples: o “for (i = 1; i <= 10; i++) { … }” instead of “for i=1:10 … end” o Two whiles: “while (condition) {…}” or “do { … } while (condition)” o Semicolons are needed after every statement except those that precede a }. o Comments are indicated by “/* …C… */” and “// … C++/Java”  C programs start with main() and usually have several functions in one file. Java/C++ have one “class” per file, which is a data structure plus all the associated functions, some of which are declared to be accessible from outside the file and others are private. MATLAB uses file names to name functions. (Actually, you can have helper functions inside a single file, too.)  MATLAB and C are procedural languages, emphasizing the function/subroutine. C++ and Java are “object oriented,” which emphasize the abstract data type and encourage code re-use through inheritance and library building.  MATLAB and Java check types while the program is running. C and C++ check types at compilation time, which means that the program is faster.  C and C++ rely on pointers, which indicate variables by their location in memory and leave it to the programmer to interpret what type of value is there. Java uses references, which always know the type of what they are pointing to.  MATLAB shows its Fortran roots in column-major storage order, use of global variables, lack of pointers or references, etc.  In C and C++ you must manage the use of memory. Java & MATLAB do garbage collection to clean up unused memory for you.  The C/C++/Java languages and some libraries are standardized by international committees. Thus, many companies produce different development environments, with different libraries, compilers, debuggers, and editors, for C/C++/Java. MATLAB comes only from Mathworks, although R and Opal are “knock-offs.” http://www.cprogramming.com/tutorial.html http://java.sun.com/docs/books/tutorial/ http://www.physics.drexel.edu/courses/Comp_Phys/General/C_basics/c_tutorial.html

3 Dec 2007

Development of a program in MATLAB and C

Levitt's puzzle problem :

Given n=10,000 atoms in a unit box [0..1]^3 with charges ci = ±1, find all pairs ij with

distance dij < a threshold t (default 0.1) and return total as quickly as possible.

We start with a simple version:

function [total, count] = levitt1(pts, threshold) % Levitt's puzzle problem: charge = pts(1,:); pts = pts(2:4,:); total = 0; count = 0; % initialize for loops for i = 2:n for j = 1:i-1 % for each pair with j<i d = norm(pts(:,i)-pts(:,j)); % find distance if (d < threshold) count = count+1; %let's count those within threshold total = total + charge(i).charge(j)/d; % and add to total end end end fprintf('Total %f comes from %d pairs, or %f6.2%%\n', total, count, 100count/(n*(n-1)/2));

We can speed this up a bit by using vector operations for the inner loop.

function [total, count] = levitt2(threshold) % Levitt's puzzle problem: charge = pts(1,:); pts = pts(2:4,:); total = 0; count = 0; for i = n:-1:2 % vectorize the inner loop p = repmat(pts(:,i),1,i-1); % copy atom at pts(:,i) v = sum((p-pts(:,1:(i-1))).^2); % find squared distances to all atoms with index j<i vt = (v<=thresh); % find which are below threshold count = count + sum(vt); total = total + sum(charge(i).charge(vt)./sqrt(v(vt))); % find which ones we need to keep end fprintf('Total %f comes from %d pairs, or %f6.2%%\n', total, count, 100count/(n*(n-1)/2));

MATLAB actually lets us write a C program and call it from MATLAB.

Running this on 10,000 points:

>> tic; levitt1(pts, 0.1); toc

Total -1025.559858 comes from

185753 pairs, or 0.37%

Elapsed time is 315.347185 seconds.

Running this on 10,000 points:

>> tic; levitt2(pts, 0.1); toc

Total -1025.559858 comes from

185753 pairs, or 0.37%

Elapsed time is 8.077751 seconds.

We write the mexFunction, using C functions that MATLAB gives us to send error messages, access variables of given types, find matrix dimensions, etc. After checking all the input and creating output variables, it calls the C function dosum(). /* Copied and modified from the MATLAB documentation

  • This function sets up the input and output variables
  • and checks that they are ok. */ void mexFunction( int nlhs, mxArray plhs[], / left hand side = output variables / int nrhs, const mxArray prhs[]) / right hand side = input variables / { double pts,total; / our names for the inputs & outputs / double thresh; int m,n; / Check for proper number of arguments. / / NOTE: You do not need an else statement when using mexErrMsgTxt within an if statement. It will never get to the else statement if mexErrMsgTxt is executed. (mexErrMsgTxt breaks you out of the MEX-file.) / if(nrhs!=2) mexErrMsgTxt("Two inputs required."); if(nlhs>1) mexErrMsgTxt("One output required."); / Check to make sure the second input argument is a scalar. / if( !mxIsDouble(prhs[1]) || mxGetN(prhs[1])mxGetM(prhs[1])!=1 ) { mexErrMsgTxt("Input threshhold must be a scalar."); } / Get the scalar input thresh. / thresh = mxGetScalar(prhs[1]); / Create a pointer to the input matrix of points. / pts = mxGetPr(prhs[0]); / Get the dimensions of the matrix input pts. / m = mxGetM(prhs[0]); n = mxGetN(prhs[0]); if (m != 4) mexErrMsgTxt("Expected 4 numbers per point: x,y,z,charge"); / Set the output pointer to total, a scalar. / plhs[0] = mxCreateDoubleMatrix(1,1, mxREAL); / Create a C pointer to a copy of the output matrix. / total = mxGetPr(plhs[0]); / Do the work */ total[0] = dosum(pts, thresh, n); }