将向量乘以Matlab中矩阵的逆矩阵

时间:2015-03-21 11:15:22

标签: matlab matrix-multiplication

我有一个问题是在Matlab中将向量乘以矩阵的逆矩阵。我正在使用的代码如下:

% Final Time
T = 0.1;

% Number of grid cells
N=20;
%N=40;
L=20;
% Delta x
dx=1/N

% define cell centers
%x = 0+dx*0.5:dx:1-0.5*dx;
x = linspace(-L/2, L/2, N)';
%define number of time steps
NTime = 100; %NB! Stability conditions-dersom NTime var 50 ville en fått helt feil svar pga lambda>0,5
%NTime = 30;
%NTime = 10;
%NTime = 20;
%NTime = 4*21;
%NTime = 4*19;


% Time step dt
dt = T/NTime

% Define a vector that is useful for handling teh different cells
J  = 1:N;    % number the cells of the domain
J1 = 2:N-1;  % the interior cells 
J2 = 1:N-1;  % numbering of the cell interfaces 

%define vector for initial data
u0 = zeros(1,N);
L = x<0.5;
u0(L)  = 0;
u0(~L) = 1;

plot(x,u0,'-r')
grid on
hold on

% define vector for solution
u = zeros(1,N);
u_old = zeros(1,N);

% useful quantity for the discrete scheme
r = dt/dx^2
mu     = dt/dx;

% calculate the numerical solution u by going through a loop of NTime number
% of time steps
A=zeros(N,N);

alpha(1)=A(1,1);
d(1)=alpha(1);
b(1)=0;                
c(1)=b(1);
gamma(1,2)=A(1,2);

% initial state
u_old = u0;

pause

for j = 2:NTime
A(j,j)=1+2*r;
    A(j,j-1)=-(1/dx^2);
    A(j,j+1)=-(1/dx^2);
u=u_old./A;
    % plotting
    plot(x,u,'-')
    xlabel('X')
    ylabel('P(X)')
    hold on
    grid on
    % update "u_old" before you move forward to the next time level
    u_old = u;

    pause


end

hold off

我得到的错误信息是:

Matrix dimensions must agree.

Error in Implicit_new (line 72)
u=u_old./A;

因此我的问题是如何在Matlab中执行u = u_old * [A ^( - 1)]?

大卫

1 个答案:

答案 0 :(得分:1)

正如knedlsepp所说,v./A是元素划分,这不是你想要的。你可以使用

  • v/A,前提是v是行向量,其长度等于A中的列数。结果是行向量。

  • A\v,前提是v是列向量,其长度等于A中的行数

结果仅在形状上有所不同:v/AA'\v'

的转置