سؤال

I'm trying to do some basic arithmetic within a for loop in MatLab.

Basically I want to copy and operate on each element one-by-one. First I want to subtract 3.6: testDataMean from each element, raise each element to the power of 2 then sum up each variable. The finally divide the variable s by 5 (sizeOfTestData)

This should calculate approximately ~1.05.

The testData variable is a 1x5 vector containing the numbers 3, 4, 2, 5, 4

   s = 0;

for k = 1:sizeTestData
    p = testData(k);
    q = p - testDataMean;
    r = q^2;
    s = s + r;
    s/5;

end

This loop actually throws an error on the last line s = s + r. I am aware I can use the sum function in most circumstances when operating on vectors of the same size, but in the context of a for loop I'm not sure.

هل كانت مفيدة؟

المحلول

Note that sum(s) / numel(s) by definition is the same as mean(s).

The loop free approach:

testData = [3, 4, 2, 5, 4]
q = testData - mean(testData);
s = mean(q.^2);
s = 1.0400

The one-liner:

s = mean((testData-mean(testData)).^2)
s = 1.0400

And your initial approach:

(After bug fixing)

testData = [3, 4, 2, 5, 4]

s = 0;
sizeTestData = length(testData);
testDataMean = mean(testData);

for k = 1:sizeTestData
   p = testData(k);
   q = p - testDataMean;
   r = q^2;
   s = s + r;  
end
s = s / numel(s);
s = 1.0400
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top