finding and changing values in matrix that satisfies 2 conditions
이전 댓글 표시
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
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
2017년 2월 12일
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
카테고리
도움말 센터 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!