# Calculating mean and variance , iris dataset

10 views (last 30 days)
mary keshtkar on 6 Nov 2022
Commented: Kevin Holly on 6 Nov 2022
I would like to calculate mean an variance for iris dataset(for the first species) . How can i clean my code! Make it two for loop (one loop for mean , one loop for variance?
a=meas(1:50,1:end);
a1=a(1:50,1);
a2=a(1:50,2);
a3=a(1:50,3);
a4=a(1:50,4);
s1=0;
for i=1:50;
s1=s1+a1(i);
end
mean1=s1/50
s2=0;
for j=1:50;
s2=s2+a2(j);
end
mean2=s2/50
s3=0;
for k=1:50;
s3=s3+a3(k);
end
mean3=s3/50
s4=0;
for l=1:50;
s4=s4+a4(l);
end
mean4=s4/50
means=[mean1,mean2,mean3,mean4]
v1=0;
for p=1:50;
v1=v1+(a1(p)-mean1)^2;
end
var1=v1/49
v2=0;
for o=1:50;
v2=v2+(a2(o)-mean2)^2;
end
var2=v2/49
v3=0;
for u=1:50;
v3=v3+(a3(u)-mean3)^2;
end
var3=v3/49
v4=0;
for t=1:50;
v4=v4+(a4(t)-mean4)^2;
end
var4=v4/49
totalvar=[var1 var2 var3 var4]

Kevin Holly on 6 Nov 2022
Is there a reason why you aren't using the mean and var function?
a=meas(1:50,1:end);
means = mean(a)
means = 1×4
5.0060 3.4280 1.4620 0.2460
totalvar = var(a)
totalvar = 1×4
0.1242 0.1437 0.0302 0.0111
Kevin Holly on 6 Nov 2022
Also, if you are allowed to use sum function:
a=meas(1:50,1:end);
means = sum(a(1:50,:))/50
means = 1×4
5.0060 3.4280 1.4620 0.2460
totalvar = sum((a(1:50,:)-means).^2)/49
totalvar = 1×4
0.1242 0.1437 0.0302 0.0111