David
David

Reputation: 159

Multiplying a vector times the inverse of a matrix in Matlab

I have a problem multiplying a vector times the inverse of a matrix in Matlab. The code I am using is the following:

% 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

The error message I get is:

Matrix dimensions must agree.

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

My question is therefore how it is possible to perform u=u_old*[A^(-1)] in Matlab?

David

Upvotes: 0

Views: 841

Answers (1)

user3717023
user3717023

Reputation:

As knedlsepp said, v./A is the elementwise division, which is not what you wanted. You can use either

  • v/A provided that v is a row vector and its length is equal to the number of columns in A. The result is a row vector.

  • A\v provided that v is a column vector and its length is equal to the number of rows in A

The results differ only in shape: v/A is the transpose of A'\v'

Upvotes: 1

Related Questions