Change value in a matrix with a conditional statement

조회 수: 4 (최근 30일)
Jalu Naradi
Jalu Naradi 2018년 6월 25일
답변: Sri Harish G 2018년 6월 27일
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에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by