Unable to perform assignment because the size of the left side is 15-by-16 and the size of the right side is 16-by-16.
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
could you please tell me how to fix this code?
% Define the mesh size
h = 0.25;
% Define the number of grid points along one edge of the square
n = 16;
% Define the first row of B
v = [-4, 1, zeros(1, n - 3), 0];
% Create the Toeplitz matrix B
B = toeplitz(v);
% Create the block diagonal matrix A
A = blkdiag(B, B);
for i = 1:n-2
A = blkdiag(A, B);
end
% Create the super diagonal and sub diagonal matrices
d2 = ones(n-1,1);
d3 = ones(n-1,1);
d2(n-1) = 0;
d3(1) = 0;
D2 = diag(d2,1);
D3 = diag(d3,-1);
% Add the super and sub diagonal blocks to A
for i = 1:n-2
A((i*(n-1)+1):((i+1)*(n-1)), (i*(n-1)+1):((i+1)*(n-1))+1) = D2;
A((i*(n-1)+1):((i+1)*(n-1))-1, (i*(n-1)+1):((i+1)*(n-1))) = D3;
end
% Define the right-hand side vector RHS
RHS = zeros((n-1)^2, 1);
for i = 1:n-1
RHS(i) = feval(@(y) (y^2), (i-1)*h);
RHS((n-1)*(n-2)+i) = feval(@(y) (y^2), 4);
end
for i = 2:n-2
RHS((i-1)*(n-1)+1) = k*feval(@(y) (y^2), 0);
RHS(i*(n-1)) = feval(@(y) (y^2), 4);
end
% Solve the system AU = RHS
U = A\RHS;
% Reshape the solution vector into a matrix
U = reshape(U, [n-1, n-1]);
% Add the boundary conditions to the solution matrix
U = [zeros(n-1,1), U, zeros(n-1,1)];
U = [zeros(1,n+1); U; h^2*(0:(n+1)).^2];
% Plot the solution as a surface
x = 0:h:4;
y = 0:h:4;
[X,Y] = meshgrid(x,y);
surf(X,Y,U')
xlabel('x')
ylabel('y')
zlabel('u')
title('Solution of Laplace''s equation')
0 Commenti
Risposte (1)
Naman
il 20 Giu 2023
Hi nana,
This error is because of incompatible sizes of left hand and right hand side matrices.
If we put n=16 and i=1 for first iteration in the first line of the above code, we will find that it comes out to be A(15,16) = D2, but the dimension of D2 is 16x16.
Same is the case with 2nd line of above snippet i.e A(14,15) = D3, whereas the dimension of D3 is 16x16.
So there needs to be a modification in code in order to make size compatible.
Hope it helps!
0 Commenti
Vedere anche
Categorie
Scopri di più su Operating on Diagonal Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!