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
0 件のコメント
回答 (1 件)
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 件のコメント
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
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!