matrix set up for kron use and speed up.

2 Ansichten (letzte 30 Tage)
mathango
mathango am 12 Mai 2016
Beantwortet: mathango am 14 Mai 2016
Hi, I am trying an alternative way of doing explicit finite difference method to explore and use other matlab available tools. I am attempting the following algorithm which is
an(j,i)=2*a(j,i)+c1*(a(j+1,i)-2*a(j,i)+a(j-1,i)+a(j,i+1)-2*a(j,i)+a(j,i-1))-ao(j,i);
assuming dx=dy
Unfortunately I run into some problems in the following code.
% iterative method 2-D
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
n=100;
i=2:n-1;
j=2:n-1;
dx=1;
dt=0.1;
c1=dt^2/dx^2;
a=zeros(n,n);
ao=zeros(n,n);
an=zeros(n,n);
CC=2-4*c1;
an(j,i)=CC*a(j,i)+c1*(a(j+1,i)+a(j-1,i)+a(j,i+1)+a(j,i-1))-ao(j,i);
% sparse method
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
n=100;
dx=1;
dt=0.1;
c1=dt^2/dx^2;
w=zeros(n,n);
wo=zeros(n,n);
wn=zeros(n,n);
CC=2-4*c1;
K = sparse(diag(2*ones(n,1))+diag(-ones(n-1,1),1) + diag(-ones(n-1,1),-1));
I = eye(n);
K2D = kron(c1*I,K)+kron(c1*K,I);
b=[-c1 zeros(1,n-2) -c1 zeros(1,n*n-n-n) -c1 zeros(1,n-2) -c1]'.*wo; % <-- this line gives me an error
wn = 2*w-K2D*w-wo-b;

Akzeptierte Antwort

mathango
mathango am 14 Mai 2016
Hi, I managed to fix the sparse algorithm, however it is slower than simple iterative method. Have I done something wrong with the sparse method? Can it be optimized further? Is there a way to substitute for for loop ?
wo=w;
I=eye(n);
e=ones(n,1);
T=spdiags([e -4*e e],[-1 0 1],n,n);
S=spdiags([e e],[-1 1],n,n);
A=(kron(I,T)+kron(S,I))*c1;
for tt=0:dt:200
wn=2*w+A*w-wo;
for i=1:n
wm(i,:)=w((i-1)*n+1:i*n); % Convert back to matrix
end
wo=w; % curent become old
w=wn; % new become current
end

Weitere Antworten (0)

Kategorien

Mehr zu Operators and Elementary Operations finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by