MATLAB: How to replace the following code, to get the matrix

for loopoptimizationvectorization

Hi, there! I going to structure the following matrix, which has some regulations.please see the picture below: if n=4;
if n=5;
My current code is below, which has many 'for'loops.
if true
% code
function P1=transition_probabilityP1(n)
A1={zeros(n^2,n^2)};
for i=1:n-1
for j=i+1
A1{i,j}=diag(0.407*ones(1,n));
end;
end;
for i=2:n
for j=i-1
A1{i,j}=diag(0.298*ones(1,n-1),-1);
end
end
for i=1:n
for j=i
e=diag(0.295*ones(1,n-1),1);
if i==1
f=diag(0.298*ones(1,n));
A1{1,1}=e+f;
A1{1,1}(n,n)=0.593;
elseif i==n
g=diag(0.407*ones(1,n));
A1{n,n}=e+g;
A1{n,n}(1,1)=0.705;
A1{n,n}(n,n)=0.702;
else
A1{i,j}=e;
A1{i,j}(1,1)=0.298;
A1{i,j}(n,n)=0.295;
end;
end
end
ind=cellfun('isempty',A1);
[r,c]=find(ind==1);
for i=1:length(r)
A1{r(i),c(i)}=zeros(n,n);
end
P1=cell2mat(A1);
end
Is there anyone who know how to make the same matrix with less loops, less memory and compute faster. Generally, I want compute the matrix P with dimension larger than 3,200,000 * 3,200,000 ! Thank you!

Best Answer

You really just need to make a sparse diagonal matrix. This can very easily be done with spdiags. Use the last syntax: A = spdiags(B,d,m,n), which you would be calling as: A = spdiags(B,d,n^2,n^2);. The issue now is only in setting up B and d which really just requires you to replace a few values in each of the columns of B, but this can be done by finding the appropriate indices to replace (note that not all values in B will be used, so start your counting from the bottom as this function will omit unnecessary values at the top of the matrix B). Put your head to the grindstone and I'm sure you can find the patterns necessary to do this for arbitrary values of n, without loops or cell arrays. I will do it for just for the lowest diagonal:
n = 5; % Change it to 4 and verify the code works in both cases.
B = 0.298*ones(n^2,1); % Use the calculation of wherever 0.298 came from if you wish
d = -(n+1); % The diagonal where the 1st vector of B should appear
B(end-n:-n:1) = 0;
A = spdiags(B,d,n^2,n^2); % This has the lower diagonal
Q = full(A); % For visualizing the correct results.
open Q
Now, just add the columns for the other diagonals to B and add the diagonal identifier to d. Also, never use the line of code:
if true
%code
end
true is always true so the code always runs.