Indexing to subtract sections of an array
33 views (last 30 days)
Say you have an 1x80000 row vector and need to subtract by blocks of 64 every so many elements. For example
A = rand(1,80000)
B = A(1:64)-A(81:145)-A(146:210) and so on till you reach the end, which maybe not be 80,000.
I can think of a way to use a loop and construct a series to accomplish this but there must be a vectorized way of doing it. I've used things like
b = a(:,1:end-1) - a(:,2:end);
but I can't find examples where people take blocks of an array and subtract.
Adam on 15 Aug 2014
Edited: Adam on 15 Aug 2014
A = reshape( A, [ 80, numel(A)/80 ] );
A = A(1:64,:);
That is going more off your recent comment rather than your original question which is not very clear on the issue of missing out 16 out of every 80 values. I'm not 100% sure what you want to do after that, but if you just want to subtract every row/column of 64 from the first row then you can just do:
A(:,1) - sum( A(:,2:end), 2 );
More Answers (3)
Nitin on 15 Aug 2014
Suppose you have 20 elements:
Reshape to 4 rows and 5 columns
X = reshape(1:20,5,4)';
% Substract rows
Y = bsxfun(@minus,X,X(1,:));
Michael Haderlein on 15 Aug 2014
Let's bring it down to some more handsome numbers, say a row vector of 17 and you want to have blocks of three.