finding and changing values in matrix that satisfies 2 conditions

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

回答(1 个)

Star Strider
Star Strider 2017-2-12
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 个评论
Rene Sebena
Rene Sebena 2017-2-12
Thank you. This is working, but I can not implement it. In some cases I canot use B(Aidx)-1, but need to change it to specific value..
Star Strider
Star Strider 2017-2-12
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

请先登录,再进行评论。

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by