Reputation: 3
I would like to generate a 100x100 Matrix that is similar to this whereby the first line and last line are different and the middle ones are all the same but shifted along by 1.
Here is what I have for a 10x10 matrix:
>> A=[0.8 -0.2 0 0 0 0 0 0 0 0;
-0.3 0.5 -0.2 0 0 0 0 0 0 0;
0 -0.3 0.5 -0.2 0 0 0 0 0 0;
0 0 -0.3 0.5 -0.2 0 0 0 0 0;
0 0 0 -0.3 0.5 -0.2 0 0 0 0;
0 0 0 0 -0.3 0.5 -0.2 0 0 0;
0 0 0 0 0 -0.3 0.5 -0.2 0 0;
0 0 0 0 0 -0.3 0.5 -0.2 0;
0 0 0 0 0 0 0 -0.3 0.5 -0.2;
0 0 0 0 0 0 0 0 -0.3 0.7;]
B= [62; 0; 0; 0; 0; 0; 0; 0; 0; 82]
>> solution=inv(A)*B
Any help is much appreciated.
Many thanks.
Upvotes: 0
Views: 2027
Reputation: 1500
What you want is called a Band Matrix also see this
n=10;
e=ones(n,1);
A=spdiags([-0.3*e 0.5*e -0.2*e],-1:1,n,n)
now this is a sparse Matrix, where the zeros are not stored which can improve storage and speed. If you want a full matrix, simply use A=full(spdiags(...))
.
For B
do:
B=ones(10,1)*0.8;
B(1) =62;
B(10)=82;
Upvotes: 4
Reputation: 221624
Approach 1:
%%// Only this part would change when you go from your sample size of 10 to 100
N = 100;
A = zeros(N); %%// Initialize
A(1:size(A,1)+1:end) = 0.5; %%// Diagonal values
A(2:size(A,1)+1:end) = -0.3;%%// Left-to-diagonal values
A(size(A,1)+1:size(A,1)+1:end) = -0.2;%%// Right-to-diagonal values
A([1 end]) = [0.8 0.7]; %% Different scalars at the top and end
Approach 2:
N = 100; %%// Size of matrix
L = -0.3; %%// Left to diagonal values
D = 0.5; %%// Diagonal values
R = -0.2; %%// Right to diagonal values
A = D*diag(ones(N,1)) + R*diag(ones(N-1,1),1) + L*diag(ones(N-1,1),-1);
A([1 end]) = [0.8 0.7]; %% Different scalars at the top and end
Upvotes: 0
Reputation: 968
code to create A is:
A = zeros(100);
A(1,1:2) = [0.8 -0.2];
for i = 2:99
A(i,i-1:i+1) = [-0.3 0.5 -0.2];
end
A(100,99:100) = [-0.3 0.7];
you can then do B with the same template.
Upvotes: 0