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

David Fletcher
David Fletcher 2018년 3월 18일
편집: David Fletcher 2018년 3월 18일
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개)

KSSV
KSSV 2018년 3월 18일

0 개 추천

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

michaelsmith
michaelsmith 2018년 3월 18일
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.

댓글을 달려면 로그인하십시오.

Image Analyst
Image Analyst 2018년 3월 18일
편집: Image Analyst 2018년 3월 18일

0 개 추천

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에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2018년 3월 18일

편집:

2018년 3월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by