Changing elements in a MxN matrix

1 次查看(过去 30 天)
I am trying to get zeros for certain part of a Matrix to zeros
I need this matrix ones that are bolded, underlines, italic "1" to become zeros. I have been trying to figure this out for a while. I tried if statesments for row > 5 and for loops.
4 1 0 1 0 1 0 1 0 1
1 4 1 0 1 0 1 0 1 0
0 1 4 1 0 1 0 1 0 1
1 0 1 4 1 0 1 0 1 0
0 1 0 1 4 1 0 1 0 1
1 0 1 0 1 4 1 0 1 0
0 1 0 1 0 1 4 1 0 1
1 0 1 0 1 0 1 4 1 0
0 1 0 1 0 1 0 1 4 1
1 0 1 0 1 0 1 0 1 4
Here is my code:
inverse = diag(ones(10,1));
inverse = inverse*4;
for col = 1:length(domain-1)
for row = 1:10
if row == col
inverse(row+1,col) = 1;
inverse(row,col+1) = 1;
elseif mod(row+col,2) == 1
inverse(row,col) = 1;
end
end
end
matrix = inverse(Nx-1,Ny-1)

采纳的回答

per isakson
per isakson 2021-4-20
编辑:per isakson 2021-4-20
Does this help?
%%
matrix = magic(10);
matrix = triu( matrix,-4 );
matrix = tril( matrix, 4 )
matrix = 10×10
92 99 1 8 15 0 0 0 0 0 98 80 7 14 16 73 0 0 0 0 4 81 88 20 22 54 56 0 0 0 85 87 19 21 3 60 62 69 0 0 86 93 25 2 9 61 68 75 52 0 0 24 76 83 90 42 49 26 33 65 0 0 82 89 91 48 30 32 39 66 0 0 0 95 97 29 31 38 45 72 0 0 0 0 78 35 37 44 46 53 0 0 0 0 0 36 43 50 27 59
%% This is better, it only overwrites the specific diagonals
matrix = magic(10);
for k = [5,7,9]
isdiag = diag( true(10-k,1), k );
matrix( isdiag ) = 0;
isdiag = diag( true(10-k,1), -k );
matrix( isdiag ) = 0;
end
matrix
matrix = 10×10
92 99 1 8 15 0 74 0 58 0 98 80 7 14 16 73 0 57 0 41 4 81 88 20 22 54 56 0 70 0 85 87 19 21 3 60 62 69 0 28 86 93 25 2 9 61 68 75 52 0 0 24 76 83 90 42 49 26 33 65 23 0 82 89 91 48 30 32 39 66 0 6 0 95 97 29 31 38 45 72 10 0 94 0 78 35 37 44 46 53 0 18 0 77 0 36 43 50 27 59
I was fooled by your example and used a 10x10 matrix in my demos. Your title says MxN matrix.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by