# For loop count question

4 views (last 30 days)
Tsuwei Tan on 18 Apr 2019
Commented: Tsuwei Tan on 18 Apr 2019
I have a count question regarding for loop.
May I ask how to get the "count" number representing from 1 to 86625?
Or there is a better to code? Thank you!
a1=-70:5:100;
a2=-60:5:60;
a3=-50:10:50;
a4=-40:10:40;
U1=1*ones(100,1);
U2=2*ones(100,1);
U3=3*ones(100,1);
U4=4*ones(100,1);
x=0.5*ones(100,1);
y=zeros(100,1);
z=2*ones(100,1);
diff=zeros(length(a1)*length(a2)*length(a3)*length(a4),5);
% length(a1)*length(a2)*length(a3)*length(a4)=35*25*11*9=86625
for i=1:length(a1)
for ii=1:length(a2)
for iii=1:length(a3)
for iiii=1:length(a4)
y=x+a1(i)*U1+a2(ii)*U2+a3(iii)*U3+a4(iiii)*U4;
count=? % This goes from 1 to 86625 represented by i, ii, iii and iii
diff(count,1)=sqrt(sum((z-y).^2)/length(U1));
diff(count,2)=a1(i);
diff(count,3)=a2(ii);
diff(count,4)=a3(iii);
diff(count,5)=a4(iiii);
end
end
end
end

Walter Roberson on 18 Apr 2019
a1 = -70:5:100;
a2 = -60:5:60;
a3 = -50:10:50;
a4 = -40:10:40;
N_a1 = length(a1);
N_a2 = length(a2);
N_a3 = length(a3);
N_a4 = length(a4);
U1 = 1*ones(100,1);
U2 = 2*ones(100,1);
U3 = 3*ones(100,1);
U4 = 4*ones(100,1);
x = 0.5*ones(100,1);
y = zeros(100,1);
z = 2*ones(100,1);
Diff = zeros(N_a4, N_a3, N_a2, N_a1, 5);
for i=1:N_a1
for ii=1:N_a2
for iii=1:N_a3
for iiii=1:N_a4
y = x + a1(i)*U1 + a2(ii)*U2 + a3(iii)*U3 + a4(iiii)*U4;
Diff(iiii, iii, ii, i, 1) = sqrt(sum((z-y).^2)/length(U1));
Diff(iiii, iii, ii, i ,2) = a1(i);
Diff(iiii, iii, ii, i, 3) = a2(ii);
Diff(iiii, iii, ii, i, 4) = a3(iii);
Diff(iiii, iii, ii, i, 5) = a4(iiii);
end
end
end
end
Diff = reshape(diff, [], 5);
It appears to me that this could be calculated much more efficiently.
[A1, A2, A3, A4] = ndgrid(a1, a2, a3, a4);
Diff = abs(2*A1 + 4*A2 + 6*A3 + 8*A4 - 3)/2;
and now, Diff(iiii, iii, ii, i) is associated with A1(iiii, iii, iii, i), A2(iiii, iii, ii, i), A3(iiii, iii, ii, i), A4(iiii, iii, ii, i) . Which is the same as a1(iiii), a2(iii), a3(ii), a4(i)

#### 1 Comment

Tsuwei Tan on 18 Apr 2019
Thank you, that reshape makes sense!

Rik on 18 Apr 2019
Initialize count to 0 before your nested loop and do count=count+1; inside the inner loop.

#### 1 Comment

Tsuwei Tan on 18 Apr 2019
Thank you Rik, yep initiaztes a count=0; is the simplies way to represent all the iteration.

R2018b

### Community Treasure Hunt

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

Start Hunting!