0
votes

I want to create matrix in MATLAB like this enter image description here which Identitas is identity matrix, Nol is zero matrix, min1 and mina is defined in the this code MATLAB below.

clear all;
clc;
h=0.2;
x=0:h:2;
k=0.2;
t=0:k:2;
N=length(x);
J=length(t);
a=4*h^2/k;
Identitas=eye(N,N);
Nol=zeros(N,N);
min1=zeros(N,N);
for i=2:N
    for j=2:N
        if i==j
            min1(i,j)=-1;
        end
    end
end
mina=zeros(N,N);
mina(1,1)=1;
for i=2:N
    mina(i,i-1)=-a;
    mina(i,i)=a+2;
end
MK(1,1)=Identitas;
for j=2:J-1
    MK(j,j-1)=min1;
    MK(j,j)=mina;
    MK(j,j+1)=min1;
end
MK(J,J)=Identitas;

That code give me error, because MATLAB cannot store a matrix in the array. So how to make that matrix in MATLAB?

1

1 Answers

0
votes

An easy fix would be to initialize MK as a cell array containing zero N-by-N matrices, fill in the right cells, and then convert it to a matrix using cell2mat:

MK = repmat({zeros(N,N)}, [J J]);   % initialize a J-by-J cell containing N-by-N zero matrix
MK{1,1}=Identitas;
for k=2:J-1
    MK{k,k-1}=min1;
    MK{k,k}=mina;
    MK{k,k+1}=min1;
end
MK{J,J}=Identitas;

MK = cell2mat(MK);                  % convert cell to matrix

Right now you are constructing min1 and mina using for-loops, but consider using the functions diag and blkdiag.