Change certain values in a matrix

Hi all I jhave a matrix A
A=[1 1 0 0 1 1 1 0; 0 0 1 1 1 1 0 0; 1 1 0 0 1 1 0 1; 1 1 1 1 1 1 1 1; 1 1 1 1 1 1 1 1]
I would like to "correct" its columns like this:
when I have a column where the sequence "0 1 0" appears I want to be changed to "0 0 0"
AND
when I have a column where the sequence "1 0 1" appears I want to be changed to "1 1 1"
So I have finaly the matrix B
B=[1 1 0 0 1 1 1 0; 1 1 0 0 1 1 0 0; 1 1 0 0 1 1 0 1; 1 1 1 1 1 1 1 1; 1 1 1 1 1 1 1 1]
I would like to use it for a larger matrix under this concept.
Do you know how to do it?
thanks in advance!

4 comentarios

Torsten
Torsten el 29 de Dic. de 2021
Editada: Torsten el 29 de Dic. de 2021
What if the matrix has a column [1; 0; 1; 0] ?
Does if become [1 ;1; 1 ;0] or [1 ;0 ;0 ;0] ?
Nikolas Spiliopoulos
Nikolas Spiliopoulos el 29 de Dic. de 2021
I would say [1;0;0;0]
thanks!
Torsten
Torsten el 29 de Dic. de 2021
Editada: Torsten el 29 de Dic. de 2021
I would say you have to define another rule.
Nikolas Spiliopoulos
Nikolas Spiliopoulos el 29 de Dic. de 2021
ok thanks!

Iniciar sesión para comentar.

Respuestas (1)

Hornett
Hornett el 30 de Sept. de 2024
Hi Nikolas,
I have understood that you are looking to replace specific patterns in a column vector. To perform the action you can try the below code which will yeild the desired result:
A=[1 1 0 0 1 1 1 0; 0 0 1 1 1 1 0 0; 1 1 0 0 1 1 0 1; 1 1 1 1 1 1 1 1; 1 1 1 1 1 1 1 1];
B=[1 1 0 0 1 1 1 0; 1 1 0 0 1 1 0 0; 1 1 0 0 1 1 0 1; 1 1 1 1 1 1 1 1; 1 1 1 1 1 1 1 1];
X=A;
% row vector format
pattern1 = [0 1 0];
pattern2 = [1 0 1 1];
X = applyFilter(A,pattern1,[0 0 0]);
X = applyFilter(X,pattern2,[1 1 1 1]);
isequal(X,B) % Check if X is equal to B
X % Display the corrected matrix X
B % Display the desired matrix B
function X = applyFilter(A,pattern,replaceWith)
X=A;
patternSize = size(pattern,2);
for row = 1:size(A,1)- patternSize
for col = 1:size(A, 2)
isequal(A(row:row+patternSize-1, col), pattern' ); % Check if the pattern matches the current submatrix
if isequal(A(row:row+patternSize-1, col), pattern' )
X(row:row+patternSize-1, col)= replaceWith'; % Replace the submatrix with the specified values
end
end
end
end
Feel free to modify the code according your usecase. I hope it helped in resolving your issue.

Categorías

Más información sobre Characters and Strings en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 29 de Dic. de 2021

Respondida:

el 30 de Sept. de 2024

Community Treasure Hunt

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

Start Hunting!

Translated by