Calculating the sum of the absolute differences of a matrix
13 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
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
>>
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Operators and Elementary Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!