Why won't this loop populate my array ?

Hello
I'm writing a loop to populate array A with the averages of the columns of array B.
w =[100.0000 90.0000 81.0000 72.9000 65.6100;
0 110.0000 99.0000 89.1000 80.1900;
0 0 121.0000 108.9000 98.0100;
0 0 0 133.1000 119.7900;
0 0 0 0 146.4100]
B =
Columns 1 through 11
100.0000 100.0000 100.0000 100.0000 100.0000 100.0000 100.0000 100.0000 100.0000 100.0000 100.0000
90.0000 90.0000 90.0000 90.0000 110.0000 90.0000 90.0000 90.0000 110.0000 110.0000 110.0000
81.0000 81.0000 81.0000 99.0000 99.0000 81.0000 99.0000 99.0000 99.0000 99.0000 121.0000
72.9000 72.9000 89.1000 89.1000 89.1000 89.1000 89.1000 108.9000 89.1000 108.9000 108.9000
65.6100 80.1900 80.1900 80.1900 80.1900 98.0100 98.0100 98.0100 98.0100 98.0100 98.0100
Columns 12 through 16
100.0000 100.0000 100.0000 100.0000 100.000
110.0000 110.0000 110.0000 110.0000 110.000
121.0000 121.0000 121.0000 121.0000 121.000
108.9000 133.1000 133.1000 108.9000 133.100
119.7900 119.7900 119.7900 119.7900 146.410
I'm trying to create an array 'A' such that each row vector is a set of averages for the given stock price. However my output is always an array of zeros, the loop is not pushing any values to A. Please help. Thank you very much for your help in advance.
n=4
A= zeros(n+1)
for J=1:n+1;
for i=1:2^(n);%loops through every column of B
if w(J,n+1)==B(n+1,i);% if the last value of W equals the last value of B
A(J,1:end)=sum(B(:,i))/(n+1);% take the average of that column B and place it in matrix A
end
end
end
A

1 个评论

If you want the mean of the columns in B you can just use
A=mean(B)
However, the likely reason you are failing to get anything other than zeros is that the condition if w(J,n+1)==B(n+1,i) is never equating to true, so A will always equal the pre-allocation of zeros(n+1)

请先登录,再进行评论。

回答(2 个)

You need not to run a loop to get averages...read about mean. It can calculate averages along row and columns by sppecifying dimesnion. If you are stringent in using loops, check below code. Let W be your matrix of size mxn where you want to get averages of columns.
[m,n]=size(W);
iwant=zeros(1,n);
for i=1:n
iwant(I)=sum(W(:,i))/m ;
end

1 个评论

yeah thanks, I want to average each column in 'B' but arrange the averages in an array so that each row will be a set of averages relating to the same final stock price B(n+1,i).
Thats where I am having difficulty.

请先登录,再进行评论。

It looks like you have w and just want the mean of non-zero values in w, so why not simply do
A = sum(w, 1) ./ sum(w ~= 0, 1);

类别

帮助中心File Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by