如何用以下晶格树形式表示我的Matlab矩阵值?

如何用以下晶格树形式表示我的Matlab矩阵值?,matlab,matrix,format,Matlab,Matrix,Format,我在矩阵中有我的晶格值,如图1所示: 图1:我的代码当前在Matlab中显示的值格式 现在,我想以晶格树的形式表示这些值,如图2所示(注意,图2中的值与图1中的值不同,图2仅用于演示目的)。我如何在Matlab中修改代码,以得到如图2所示的树格式的结果 图2:我希望在Matlab结果中显示的值格式 以下是我的代码: function [price,BLOV_lattice]=BLOV_general(S0,K,sigma,r,T,nColumn) %% Constant paramete

我在矩阵中有我的晶格值,如图1所示:

图1:我的代码当前在Matlab中显示的值格式

现在,我想以晶格树的形式表示这些值,如图2所示(注意,图2中的值与图1中的值不同,图2仅用于演示目的)。我如何在Matlab中修改代码,以得到如图2所示的树格式的结果

图2:我希望在Matlab结果中显示的值格式

以下是我的代码:

function [price,BLOV_lattice]=BLOV_general(S0,K,sigma,r,T,nColumn)


%% Constant parameters
del_T=T./nColumn; % where n is the number of columns
u=exp(sigma.*sqrt(del_T));
d=1./u;
p=(exp(r.*del_T)-d)./(u-d);
a=exp(-r.*del_T);

%% Initializing the lattice
Stree=zeros(nColumn+1,nColumn+1);
BLOV_lattice=zeros(nColumn+1,nColumn+1);

%% Developing the lattice

for i=0:nColumn
    for j=0:i
        Stree(j+1,i+1)=S0.*(u.^j)*(d.^(i-j));
    end
end
for i=0:nColumn
    BLOV_lattice(i+1,nColumn+1)=max(Stree(i+1,nColumn+1)-K,0);
end
for i=nColumn:-1:1
    for j=0:i-1
        BLOV_lattice(j+1,i)=a.*(((1-p).*BLOV_lattice(j+1,i+1))+(p.*BLOV_lattice(j+2,i+1)));
    end
end
price=BLOV_lattice(1,1);

我看到一个只使用一个for循环的解决方案

function B = newShape(A)

n = size(A,1);
B = zeros(2*n-1,n);
idx0 = n:(2*n):(2*n^2 - n);
B(idx0(1):(2*n-2):(2*n^2-n-1)) = A(1,:);
for i=n:(2*n-2)
    B( idx0(i - n + 2):(2*n-2):(2*n^2-n) ) = A(i-(n-1)+1,i-(n-1)+1:end);
end


end

如果您的目标是将一个上三角矩阵(如图1所示)重新格式化为一个以树状结构(如图2所示)排列的非零值矩阵,那么您可以使用函数来实现这一点。下面是一个使用5乘5矩阵的示例:

>> A = triu(reshape(1:25,5,5))  %# A sample upper-triangular matrix

A =

     1     6    11    16    21
     0     7    12    17    22
     0     0    13    18    23
     0     0     0    19    24
     0     0     0     0    25

>> N = size(A,1);  %# The size of the rows and columns in A
>> B = full(spdiags(spdiags(A),(1-N):2:(N-1),zeros(2*N-1,N)))

B =

     0     0     0     0    21
     0     0     0    16     0
     0     0    11     0    22
     0     6     0    17     0
     1     0    12     0    23
     0     7     0    18     0
     0     0    13     0    24
     0     0     0    19     0
     0     0     0     0    25

你好,马克:我猜是
A
这里是
BLOV\u lattice
?我尝试了你的代码,但它给出了一个错误???索引超过了矩阵维数。对于此行
B(idx0(i-n+2):(2*n-2):(2*n^2-n))=A(i-(n-1)+1,i-(n-1)+1:end)什么是
A
?如果它的
BLOV_晶格
那么它就不必是正方形,我假设
A
是正方形。例如,我能够做
[pa]=BLOV_-general(10,5,3,05,1,20)
BLOV=newShape(A)我明白。我就是这样尝试的。然而,树结构取决于列的数量,不一定是正方形。