Error: Incorrect dimensions for matrix multiplication
2 次查看(过去 30 天)
显示 更早的评论
I have the following code which is an iterative solver that solves for a linear poisson's equation as a simple test:
clearvars; clc; close all;
N=30;
[D,x] = cheb(N); D2 = D^2;
D2(N+1,:) = D(N+1,:); %Neumann BC at left endpoint (x=-1), esp w/ D
D2 = D2(2:N+1,2:N+1); %Dirichlet BC at right endpoint (x=1)
u = (exp(4*x) - 4*exp(-4)*(x-1)-exp(4))/16; %w/ BCs ux(-1)=u(1)=0
n =ones(size(u));
%build source term
dndx = D *n;
dudx = D *u;
prod1 = dndx .* dudx;
du2dx = D * dudx;
prod2 = n .*du2dx;
invN = (1./n) ;
source = prod1(2:N) + prod2(2:N);
uold = ones(size(u(2:N)));
max_iter =500;
err_max = 1e-8;
for iterations = 1:max_iter
phikmax_old = (max(abs(uold)));
duoldx = D(2:N,2:N) *uold;
dnudx = dndx(2:N) .* duoldx;
ffh = source;
RHS = ffh - dnudx;
Stilde = invN(2:N) .* RHS;
unew = D2\[Stilde;0];
phikmax = (max(abs(unew)));
if phikmax < err_max
it_error = err_max /2;
else
it_error = abs( phikmax - phikmax_old) / phikmax;
end
if it_error < err_max
break;
end
uold = unew;
end
unew = [0;unew];
figure
plot(x,unew,'--rs',x,(u));
legend('Num solution','Exact solution')
Function cheb:
function [ D, x ] = cheb ( N )
if ( N == 0 )
D = 0.0;
x = 1.0;
return
end
x = cos ( pi * ( 0 : N ) / N )';
c = [ 2.0; ones(N-1,1); 2.0 ] .* (-1.0).^(0:N)';
X = repmat ( x, 1, N + 1 );
dX = X - X';
D = ( c * (1.0 ./ c )' ) ./ ( dX + ( eye ( N + 1 ) ) );
D = D - diag ( sum ( D' ) );
return
end
I get the correct solution at the first iteraion " for iterations = 1 %1:max_iter" then after that I get the error:
Error using *
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of
rows in the second matrix. To perform elementwise multiplication, use '.*'.
Error in Filename (line 298)
duoldx = D(2:N,2:N) *uold;
which I believe it has to do with uold not being same size as unew? How can I fix that? Thanks
1 个评论
Mathieu NOE
2023-10-13
hello
your array uold has length = 29 at the first iteration and 30 at the second (when you do: uold = unew;)
there is something to fix in your code when you update some data as their dimensions change (and should not) as the loop iterates
回答(1 个)
Torsten
2023-10-13
You set uold = unew, but unew is 30x1 instead of 29x1.
Since D(2:N,2:N) is 29x29, MATLAB errors in the next iteration when you try to compute
duoldx = D(2:N,2:N) *uold;
2 个评论
Torsten
2023-10-13
Maybe by setting
uold = unew(2:N);
instead of
uold = unew;
?
But it's just to make the code work technically without knowledge about what you have programmed.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!