How to fill a matrix in a specific way

1 次查看(过去 30 天)
I have a 5x5 matrix of 0's defined as P below. What I want to do is fill it out to become the commented out matrix also seen below. What is the best way of going about populating the matrix with the pattern seen in the commented out matrix? Let me know if the pattern isn't clear. You essentially have a pattern of u 0.1 h and that moves throughout the matrix going down the columns.
N = 5;
P = zeros(N,N);
h = 5.2;
u = 1.7;
%{
P = [0.1 h 0 0 0 ; ...
u 0.1 h 0 0; ...
0 u 0.1 h 0; ...
0 0 u 0.1 h; ...
0 0 0 u 0.1];
%}

回答(1 个)

Akira Agata
Akira Agata 2017-2-17
编辑:Akira Agata 2017-2-17
I think diag function will help.
https://www.mathworks.com/help/matlab/ref/diag.html
Please try the following script.
N = 5;
h = 5.2;
u = 1.7;
P = diag(repmat(0.1,1,5)) + diag(repmat(u,1,4),-1) + diag(repmat(h,1,4),1);

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by