필터 지우기
필터 지우기

define the 1/K strategy

조회 수: 2 (최근 30일)
Qian cao
Qian cao 2015년 11월 1일
댓글: Qian cao 2015년 11월 1일
Hi, I have a matrix
B =
0 9 7 0 0
0 9 7 6 0
0 2 7 6 0
8 0 4 2 0
rows represent time series and columns represent assets. In each row ( time) I need to get a strategy which allocates 1 equally to assets that do not equal zero. The results for the strategy s should =[0 1/2 1/2 0 0; 0 1/3 1/3 1/3 0;0 1/3 1/3 1/3 0;1/3 0 1/3 1/3 0]. My code is as follows but I am looking for a more efficient solution. Thank you.
weight=zeros(4,5);
for r=1:4
countzero=0;
index=[];
for c=1:5
if B(r,c)==0
weight(r,c)=0;
else countzero=countzero+1;
index=[index,c];
end
end
weight(r,index)=1/countzero;
end

채택된 답변

John D'Errico
John D'Errico 2015년 11월 1일
편집: dpb 2015년 11월 1일
Learn to think in terms of matrices, and operations on them. Finally, learn to use tools like bsxfun, which helps greatly on these problems.
You want to create a new matrix, with zero where you have zeros, and 1 over the number of non-zeros in that row of your array.
W = (B ~= 0);
W = bsxfun(@rdivide,W,sum(W,2));
W =
0 0.5 0.5 0 0
0 0.33333 0.33333 0.33333 0
0 0.33333 0.33333 0.33333 0
0.33333 0 0.33333 0.33333 0
  댓글 수: 1
Qian cao
Qian cao 2015년 11월 1일
Thank you a lot!!

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

추가 답변 (1개)

dpb
dpb 2015년 11월 1일
wt=bsxfun(@rdivide,B>0,sum(B>0,2));
  댓글 수: 1
Qian cao
Qian cao 2015년 11월 1일
Many thanks:)

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

카테고리

Help CenterFile Exchange에서 Financial Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by