Effacer les filtres
Effacer les filtres

Change value in a matrix with a conditional statement

1 vue (au cours des 30 derniers jours)
Jalu Naradi
Jalu Naradi le 25 Juin 2018
I have a matrix [3000,1000] which only consist of 1,-1,0,-2. If there is -1 in a row followed by any consecutive zeros then followed by 1, this 1 value should change to 2. But if this -1 is followed by any consecutive zeros then followed by -2 and then followed by 1, this 1 value should remain the same.
For example
A = [0 -1 0 0 1 0 -1 0 0 0 0 -2 0 0 0 1;
-1 0 0 -2 0 1 0 0 0 -1 0 0 0 0 1 0]
should change to
A = [0 -1 0 0 2 0 -1 0 0 0 0 -2 0 0 0 1;
-1 0 0 -2 0 1 0 0 0 -1 0 0 0 0 2 0]
Any suggestion would be very helpful.
Thank you

Réponses (1)

Sri Harish G
Sri Harish G le 27 Juin 2018
If you are unwilling to iterate through the matrix and change the 1s at the appropriate location to a 2, you could convert the rows of the matrix to a string and search for the regular expression '-1[0]*1' and replace the element in the ending index of all matches with a 2.
https://www.mathworks.com/help/matlab/ref/regexp.html
Example:
>> A=[0 -1 0 0 1 0 -1 0 0 0 0 -2 0 0 0 1;
-1 0 0 -2 0 1 0 0 0 -1 0 0 0 0 1 0];
>>B=cellstr(num2str(A))
B =
2×1 cell array
{' 0 -1 0 0 1 0 -1 0 0 0 0 -2 0 0 0 1'}
{'-1 0 0 -2 0 1 0 0 0 -1 0 0 0 0 1 0'}
>>C=regexp(B,'-1[ 0 ]*1','end')
C =
2×1 cell array
{[14]}
{[44]}
>>B=arrayfun(@(x,y) replace(x,y),B,C)
Where function replace is defined as:
function out = replace(x,y)
x{1}(y{1})='2';
out=x;
end
This will give
B =
2×1 cell array
{' 0 -1 0 0 2 0 -1 0 0 0 0 -2 0 0 0 1'}
{'-1 0 0 -2 0 1 0 0 0 -1 0 0 0 0 2 0'}
>>A=str2num(cell2mat(B))
A = [0 -1 0 0 2 0 -1 0 0 0 0 -2 0 0 0 1;
-1 0 0 -2 0 1 0 0 0 -1 0 0 0 0 2 0]

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by