Storing maximum values from each iteration

1 view (last 30 days)
hi guys. below is my code. i'm trying to save the maximum values at each iteration of the for loop h1 = 0.02:0.001:0.03 (that is [maxUd1,indexUd1] at h1 = 0.02, [maxUd1,indexUd1] at h1 = 0.021,...., [maxUd1,indexUd1] at h1 = 0.03). how do i go about this please?
for h1 = 0.02:0.001:0.03;
c1 = 0.01;
X1 = 0.3;
Ud1 = zeros(11,11,11,11);
for a1 = 0:0.1:1;
for d1 = 0:0.1:1
Ud1(pA1,pd11,pd21,pd31) = h1*(d1/(a1+d1)) * (1-X1) - c1*d1
[maxUd1,indexUd1] = max(Ud1(:));
end
end
end

Accepted Answer

Walter Roberson
Walter Roberson on 22 Jul 2017
h1_values = 0.02:0.001:0.03;
a1_values = 0:0.1:1;
d1_values = 0:0.1:1;
num_h1 = length(h1_values);
num_a1 = length(a1_values);
num_d1 = length(d1_values);
%for efficiency the first index should be the inner loop index
maxUd1 = zeros(num_d1, num_a1, num_h1);
indexUd1 = maxUd1;
for h1_idx = 1 : num_h1
h1 = h1_values(h1_idx);
c1 = 0.01;
X1 = 0.3;
Ud1 = zeros(11,11,11,11);
for a1_idx = 1 : num_a1
a1 = a1_values(a1_idx);
for d1_idx = 1 : num_d1
d1 = d1_values(d1_idx);
%why are you storing what appears to be a scalar into an array at constant indices??
Ud1(pA1,pd11,pd21,pd31) = h1*(d1/(a1+d1)) * (1-X1) - c1*d1;
[maxUd1(d1_idx, a1_idx, h1_idx), indexUd1(d1_idx, a1_idx, h1_idx)] = max(Ud1(:));
end
end
end
%now that we completed the arrays, flip them around so the first index is the
%h1 index and the last one is the d1 index
maxUd1 = permute(maxUd1, [3 2 1]);
indexUd1 = permute(indexUd1, [3 2 1]);
  4 Comments
Walter Roberson
Walter Roberson on 22 Jul 2017
By the way: unless X is a vector or array, I would write all of this a quite different way -- probably by using ndgrid(), doing all of the arithmetic computations simultaneously, and then using max() on the appropriate dimension of the result.
Chiamaka Agwuegbo
Chiamaka Agwuegbo on 28 Jul 2017
Thank you very much. It worked. I apologize for the late reply. My system crashed.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!