Calculating the sum of the absolute differences of a matrix
13 views (last 30 days)
Show older comments
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
0 Comments
Answers (1)
per isakson
on 17 May 2018
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
>>
0 Comments
See Also
Categories
Find more on Operators and Elementary Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!