Creating a Pattern of set values within a Matrix
11 views (last 30 days)
Show older comments
Braeden Elbers
on 24 Feb 2022
Commented: Walter Roberson
on 25 Feb 2022
function B = inf_analysis(i,j,k,N)
A = ones(N^2)
B = diag(diag(A))
for rows = 1:N^2;
for cols = 1:N^2;
B(rows,rows+4:rows+4) = -1/4;
break;
end
end
I want to create a matrix with the value -1/4 is specific diagonals and locations based off a specific pattern i found. I was able to place the value in one specific diagonal but it added four more columns which i did not want.
7 Comments
Accepted Answer
Walter Roberson
on 24 Feb 2022
inf_analysis([],[],[],4)
function B = inf_analysis(i,j,k,N)
z = zeros(N^2,1);
e = ones(N^2,1);
e4 = -e/4;
B = spdiags([e4, z, e4, e, e4, z, z, e4],-3:4,N^2,N^2);
B = full(B);
end
3 Comments
Walter Roberson
on 24 Feb 2022
Slightly improved:
inf_analysis([],[],[],4)
function B = inf_analysis(i,j,k,N)
e = ones(N^2,1);
e4 = -e/4;
B = spdiags([e4, e4, e, e4, e4], [-3, -1, 0, 1, 4], N^2, N^2);
B = full(B);
end
Walter Roberson
on 24 Feb 2022
inf_analysis([],[],[],4)
function B = inf_analysis(i,j,k,N)
e = ones(N^2,1);
e4 = -e/4;
e4m1 = e4; e4m1(3:3:end) = 0;
e4p1 = e4; e4p1(1:3:end) = 0;
B = spdiags([e4, e4m1, e, e4p1, e4], [-3, -1, 0, 1, 4], N^2, N^2);
B = full(B);
end
More Answers (1)
Braeden Elbers
on 24 Feb 2022
Edited: Braeden Elbers
on 24 Feb 2022
3 Comments
Walter Roberson
on 25 Feb 2022
I suggest using repelem(), such as
repelem([y1, y2, y1, y2, y3, y2, y1, y2, y1], [1, N-2, 1, 1, ?, 1, N-2, 1])
where ? is a value you would need to calculate.
See Also
Categories
Find more on Operating on Diagonal Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!