Question #52517

Create three scripts with the program code from the third example (3-D array) in Part 3.

In one script, copy-and-paste the nested for-loop 3-D array program as given below.

In the second script, add the array pre-allocation version of the program

In the third script, insert your vectorised version of the program

Now, experiment with increasing the value of n in the original nested for-loop program, until the execution time takes over 3 seconds to run. To do this, either use the “Run and Time” button on the Editor tab – or use the tic and toc commands. Now run the equivalent second and third scripts (for the same value of n). How much faster is the vectorised solution compared with the original program code?

% 3-D array where

% C(i,j,k) = i*j+k

n = 10;

for i=1:n

for j=1:n

for k=1:n

C(i,j,k) = i*j+k;

end

end

end

In one script, copy-and-paste the nested for-loop 3-D array program as given below.

In the second script, add the array pre-allocation version of the program

In the third script, insert your vectorised version of the program

Now, experiment with increasing the value of n in the original nested for-loop program, until the execution time takes over 3 seconds to run. To do this, either use the “Run and Time” button on the Editor tab – or use the tic and toc commands. Now run the equivalent second and third scripts (for the same value of n). How much faster is the vectorised solution compared with the original program code?

% 3-D array where

% C(i,j,k) = i*j+k

n = 10;

for i=1:n

for j=1:n

for k=1:n

C(i,j,k) = i*j+k;

end

end

end

Expert's answer

Use n=150:

n onescript, copy-and-paste the nested for-loop 3-D array program as given below.

% 3-D array where

% C(i,j,k) = i*j+k

tic

n = 150;

for i=1:n

for j=1:n

for k=1:n

C(i,j,k) =i*j+k;

end

end

end

toc

Elapsed time is 5.827000 seconds.

In thesecond script, add the array pre-allocation version of the program

tic

n = 150;

C=zeros(n,n,n);

for i=1:n

for j=1:n

for k=1:n

C(i,j,k) =i*j+k;

end

end

end

toc

Elapsed time is 0.430000 seconds.

In thethird script, insert your vectorised version of the program:

tic

n = 150;

C=zeros(n,n,n);

k=linspace(1,1,n);

IJ=(k')*k;

for i=1:n

C(:,:,i)=IJ+i;

end

toc

Learn more about our help with Assignments: ProgrammingMatlab

## Comments

## Leave a comment