Change value in a matrix with a conditional statement

5 Ansichten (letzte 30 Tage)
Jalu Naradi
Jalu Naradi am 25 Jun. 2018
Beantwortet: Sri Harish G am 27 Jun. 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

Antworten (1)

Sri Harish G
Sri Harish G am 27 Jun. 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]

Kategorien

Mehr zu MATLAB Coder finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by