note that the code below is obtained from Matlab documentation except for the bottom portion.
function B = nway(A,n)
% Compute average of every N elements of A and put them in B.
if ((mod(numel(A),n) == 0) && (n>=1 && n<=numel(A)))
B = ones(1,numel(A)/n);
k = 1;
for i = 1 : numel(A)/n
B(i) = mean(A(k + (0:n-1)));
k = k + n;
end
What does the for loop code mean, especially the following line?
for i = 1 : numel(A)/n
and how does the i work by inserting it in B(i)?
A for-loop in Matlab is constructed as
The
iterationVariablewill take on the value of the first column oflistOfValuesin the first iteration of the loop, then the value of the second column, etc. You can then useiterationValuein your calculations.will therefore set the value of
ito1,2,3...up to the value of"number of elements of A divided by n".is an indexing operation, that returns the
ith element of the arrayB.As @HighPerformanceMark suggests, I very much recommend trying out these expressions at the command line, or to work through the “getting started” section of the excellent Matlab documentation.