Saving (in a matrix) the elapsed time and number of iterations for a large number of cases

3 views (last 30 days)
I have a program that outputs the *number of iterations* and a *test value*, given inputs *A1,A2,A3,A4*.
I want to run through 5 values each of A1, A2, A3, A4, thus making 625 runs. In the process, I want to save the *time elapsed* for each run, the *number of iterations*, and *test value* in 3 separate matrices.
I have tried using 4 nested *for* loops, and made progress, but need some help on indexing the elements of the matrices. The iterator variables in the for loops don't match the indexing variables...
The code for the 4 nested loops is below:
m = logspace(-4,4,5);
n = logspace(0,8,5);
eltime = zeros(5,length(m)*length(m)*length(m));
for A1 = m
for A2 = m
for A3 = m
for A4 = n
tic
SmallMAX(A1,A2,A3,A4)
toc;
for i=1:numel(eltime)
for j = 1:length(n)
eltime(j,i) = toc;
end
end
end
end
end
end
The code for the main program is excerpted below:
function [k,test] = OC(A1,A2,A3,A4)
...
end
Thanks for any help.

Accepted Answer

Walter Roberson
Walter Roberson on 18 Jul 2015
Use this kind of code framework
mvals = logspace(-4,4,5);
numm = length(mvals);
nvals = logspace(0,8,5);
numn = length(nvals);
for A1idx = 1 : numm
A1 = mvals(A1idx);
for A2idx = 1 : numm
A2 = mvals(A2idx);
for A3idx = 1 : numm
A3 = mvals(A3idx);
for A4idx = 1 : numn
A4 = nvals(A4idx);
....
eltime(A4idx, A3idx, A2idx, A1idx) = ....
end
end
end
end
You might notice that I reversed the indices from the obvious, that I did not index eltime(A1idx, A2idx, A3idx, A4idx) . You can use that order, but it is less efficient than the order I used. That is because in MATLAB memory is arranged "down columns", so A(1,1) is immediately adjacent to A(2,1) then A(3,1) rather than A(1,1) being immediately adjacent to A(1,2) then A(1,3) . It is more efficient to assign to adjacent memory.
You should also examine your code to determine whether you can vectorize it, calculating on a matrix basis instead of one value at a time. For example, A1 + A2 * A3^A4 can be vectorized as A1 + A2 .* A3 .^ A4 so now if you feed in arrays of the same size, the expression would calculate for each corresponding element. This can end up being quite a lot faster.
If your code can be vectorized, then you can use ndgrid to build the appropriate matrices:
[A1, A2, A3, A4] = ndgrid(mvals, mvals, mvals, nvals);
result = OC(A1, A2, A3, A4); %do everything at once, no loops at all!
this will not give you the individual elapsed times, but you might find that it is no longer important compared to the speedup.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!