Something weird in matlab

If you have enough memory, do the following.

a = ones(10000,1000);

Then do something like

Then compare

Case 1:
for i = 1:10
b = sqrt(a.^2);
end

Case 2:

b = sqrt(a.^2);b = sqrt(a.^2);b = sqrt(a.^2);b = sqrt(a.^2);b = sqrt(a.^2);b = sqrt(a.^2);b = sqrt(a.^2);b = sqrt(a.^2);b = sqrt(a.^2);b = sqrt(a.^2);% run in one command line

Case 3:
b = sqrt(a.^2);
b = sqrt(a.^2);
b = sqrt(a.^2);
b = sqrt(a.^2);
b = sqrt(a.^2);
b = sqrt(a.^2);
b = sqrt(a.^2);
b = sqrt(a.^2);
b = sqrt(a.^2);
b = sqrt(a.^2);
% run in separate command lines

You’ll get 1st and 2nd case run almost with the same speed (maybe different, I can’t tell significant difference.) But 3rd case will be much faster.

Why?

One Response

  1. Sorry. It’s a mistake.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: