MATLAB Answers

Changing elements in a MxN matrix

2 views (last 30 days)
WARRIOR24
WARRIOR24 on 20 Apr 2021
Edited: per isakson on 20 Apr 2021
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)

Accepted Answer

per isakson
per isakson on 20 Apr 2021
Edited: per isakson on 20 Apr 2021
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.

More Answers (0)

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by