Changing elements in a MxN matrix

조회 수: 1 (최근 30일)
WARRIOR24
WARRIOR24 2021년 4월 20일
편집: per isakson 2021년 4월 20일
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에서 Matrices and Arrays에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by