# Accelerate computation speed by using a different syntax [closed]

I was reading a book about Matlab ("Accelerating Matlab with GPU computing - A Primer with Examples" by Jung Suh and Youngming Kim, 2013. Chapter 1.7 Examples).

I read an example where it said that:

by using elemental calculation, matrix calculation, and function call instead of for loops, the speed can be dramatically accelerated.

In the case I read, it reduced calculation time from 50s to 0.5s.

My questions:

1. which syntax is more "resources saving" and "faster": function call, for, while, if, switch, and (i.e. search elements in a matrix or set) etc.?

2. How fast is the element-wise calculation, addition, and matrix calculation etc.?

For the convince of understanding, a short example was given below:

%%% First case
tic;
B = 0;
A = 1:1e8;
for i=1:1000
B = B + A(i);
end
toc;

%%% Second case
tic;
B = 0;
A = 1:1e8;
B = sum(A);
toc;

%%% Third case
C = ones(1e8,1);
tic;
B = 0;
A = 1:1e8;
B = A*C;
toc;


with the following timing results

Elapsed time is 0.463159 seconds.

Elapsed time is 0.501524 seconds.

Elapsed time is 0.532470 seconds.

In the above example, all three methods had different but comparable speed.

## closed as off-topic by Brian Borchers, Chris Rackauckas, Bill Greene, Kirill, GoHokiesJun 13 '18 at 18:56

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

• Can you provide the information about the book you are reading? – nicoguaro Jun 13 '18 at 15:51
• I think that you are referring to vectorization of operations, am I right? – nicoguaro Jun 13 '18 at 16:46
• @nicoguaro Some of this is also down to the generic optimisation differences between compiled and interpreted code. – origimbo Jun 13 '18 at 16:56
• I still think it is too broad, since the answer will be very different depending on what you try to compute. It also very much depends on the version of Matlab (and, to a degree, the hardware and operating system since matrix operations are punted to the Intel MKL library); as you notice, simple(!) for loops have become much faster in recent versions of Matlab compared to a few years ago. – Christian Clason Jun 14 '18 at 7:14
• Instead of trying to think of it in terms of which Matlab syntax is faster, which I think is a bit of a dead end, try thinking more concretely in terms of what actually gets executed on the CPU: is it running a (slow, non-JIT) interpreter over your code, or is execution dispatched to a compiled optimized function. Trying to classify different aspects of Matlab's syntax as fast or slow wouldn't get at the underlying issues and wouldn't help understand. – Kirill Jun 16 '18 at 15:37