Calculating the sum of the absolute differences of a matrix

13 Ansichten (letzte 30 Tage)
Chris Matthews
Chris Matthews am 17 Mai 2018
Beantwortet: per isakson am 17 Mai 2018
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

Antworten (1)

per isakson
per isakson am 17 Mai 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
>>

Kategorien

Mehr zu Operators and Elementary Operations finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by