MATLAB: I want to code such that the loop is constraint for two different values

for loop

I want to code this equation
s(i)=x(i)+(l1-sum(x(i))/N
here the loop must be i=1:108300
and the value for l1 and x(i) must be same for first 300
here I something I tried.
for i2=1:108300
for i3=1:300
s(i2)=W(i2)+(l1-sum(W(:,i3)))/N;
end
end

Best Answer

N = 108300;
x = rand(N,1);
sum_rows = 300;
l1 = x(1:sum_rows:N); %take every 300th value
l1_r = reshape(repmat(l1,1,sum_rows)',N,1); %repeat it
sum_x = sum(reshape(x,N/sum_rows,sum_rows),2); %create a sum of every 300 rows
sum_x_r = reshape(repmat(sum_x,1,sum_rows)',N,1); %repeat 361 times to create a vector of N length
s=x+(l1_r-sum_x_r)./N;