Calculating the sum of the absolute differences of a matrix

조회 수: 4 (최근 30일)
Chris Matthews
Chris Matthews 2018년 5월 17일
답변: per isakson 2018년 5월 17일
Hi all,
I have matrix X
x=[0 0 1 2 4 2 5 1 0 0 3 7 9 6 9 0 0 0 0 3 7 0 0 0 2];
how I could calculate the sum of the differences of the absolute values of the first 3 values from the last zero in the string of zeros?
So my output should be:
out = [ (1-0 + 2-1 + 4-2) , (3-0 + 7-3 + 9-7), .....], therefore
out = [ 4, 9....]
Please note that in my actual matrix X, there are positive and negative values so that's why I need the code to take the absolute value.
Thanks guys! Chris

답변 (1개)

per isakson
per isakson 2018년 5월 17일
Here is a script that builds on my answer to your last question
x = [0 0 1 2 4 2 5 1 0 0 3 7 9 6 9 0 0 0 0 3 7 0 0 0 2];
% add trailing [0,0] to avoid the risk of referencing outside x.
x(end+1:end+2) = [0,0];
dx = [ 0, diff( x ) ];
is0 = [ false, ( x == 0 ) ];
is0(end) = [];
ix_start = find( is0 & not(dx==0) );
an1 = nan( size( ix_start ) );
an2 = cell( size( ix_start ) );
for jj = 1 : length( ix_start )
an1(jj) = sum( x( ix_start(jj) : ix_start(jj)+2 ) );
an2{jj} = abs( x( ix_start(jj) : ix_start(jj)+2 ) ) ...
- abs( x( ix_start(jj)-1 : ix_start(jj)+1 ) );
end
inspect new result
>> an2{:}
ans =
1 1 2
ans =
3 4 2
ans =
3 4 -7
ans =
2 -2 0
>>

카테고리

Help CenterFile Exchange에서 Multirate Signal Processing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by