# finding and changing values in matrix that satisfies 2 conditions

1 view (last 30 days)
Rene Sebena on 12 Feb 2017
Commented: Star Strider on 12 Feb 2017
Hi there, I am new in matlab and try to solve this problem. I have vector which contains various triggers and a lot of zeros: A=[0;0;0;0;0;0;0;0;2;0;0;1;0;0;0;0;0;0;0;0;3;0;0;0;1;0;0;0;0;0;0;0;4;0;1;0;0;0;0;0;0;0;0;5;1]; I need to find first non zero value (in this case the 9th value "2") and then from this point every second nonzero value and change it to other value. My code (see bellow) identifies the values but is not changing them. Any idea why? Thank you for your time and help.
idx = find(A > 0);
B=A;
for i = idx(1:2:20);
if B(i)==2; B(i)=1;end
if B(i)==3; B(i)=2;end
if B(i)==4; B(i)=3;end
if B(i)==5; B(i)=4;end
end

Star Strider on 12 Feb 2017
See if this does what you want:
A=[0;0;0;0;0;0;0;0;2;0;0;1;0;0;0;0;0;0;0;0;3;0;0;0;1;0;0;0;0;0;0;0;4;0;1;0;0;0;0;0;0;0;0;5;1];
idx = find(A > 0);
Aidx = idx(1:2:end);
B=A;
B(Aidx) = B(Aidx)-1; % Desired Result
Compare = [A'; B'] % See Result & Compare (Delete)
Compare =
Columns 1 through 16
0 0 0 0 0 0 0 0 2 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0
Columns 17 through 32
0 0 0 0 3 0 0 0 1 0 0 0 0 0 0 0
0 0 0 0 2 0 0 0 1 0 0 0 0 0 0 0
Columns 33 through 45
4 0 1 0 0 0 0 0 0 0 0 5 1
3 0 1 0 0 0 0 0 0 0 0 4 1
##### 2 CommentsShow 1 older commentHide 1 older comment
Star Strider on 12 Feb 2017
My pleasure.
Is there any pattern to the specific value you need to change the different values to?
In your example, there are 4 values that need to be changed, so if you want to change them respectively to 5, 9, 7 and 3 (chosen arbitrarily), this works:
A=[0;0;0;0;0;0;0;0;2;0;0;1;0;0;0;0;0;0;0;0;3;0;0;0;1;0;0;0;0;0;0;0;4;0;1;0;0;0;0;0;0;0;0;5;1];
idx = find(A > 0);
Aidx = idx(1:2:end);
B=A;
B(Aidx) = [5 9 7 3]; % Desired Result
Compare = [A'; B'] % See Result & Compare (Delete)
Compare =
Columns 1 through 16
0 0 0 0 0 0 0 0 2 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 5 0 0 1 0 0 0 0
Columns 17 through 32
0 0 0 0 3 0 0 0 1 0 0 0 0 0 0 0
0 0 0 0 9 0 0 0 1 0 0 0 0 0 0 0
Columns 33 through 45
4 0 1 0 0 0 0 0 0 0 0 5 1
7 0 1 0 0 0 0 0 0 0 0 3 1