Change value in a matrix with a conditional statement

1 次查看(过去 30 天)
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

回答(1 个)

Sri Harish G
Sri Harish G 2018-6-27
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]

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by