How to index a matrix into segments
Question
I have a matrix that is 1 column with 5448 rows with values in each. In reality these 5448 values are divided into 12 taps (being 454 values per tap). I want to index the closest 10% of values closest to tap boundaries (10% of a tap is 45.4 values so lets say 45 values). For the first tap, i will only need the last 10%, and for the last tap (tap 12) i will only need the first 10%. Every other tap (2-11) i will need the beginning 10% and the last 10%. So essentially the first 45 values and the last 45 values of each tap.
currently I'm extracting the value segments like this:
A1 = interpolate((817/2+.5):(908/2),:);
B1 = interpolate((909/2+.5):(1000/2),:);
this example includes the last 10% values of tap 1 and the first 10% values from tap 2. If i only had a few segments to pull this would be okay, but when i have matrices that go up to around 40,000 values, this method gets a little rediculous.
Solution
I'd make a function to get these values, to avoid making silly mistakes (and to make it easier if you change your tap size or percentage):
function [A, B] = GetTapBoundaries( arr, tapNum, tapSize )
sliceSize = floor(tapSize * 0.1);
boundaryIdx = (tapNum-1) * tapSize; % last element in previous tap
leftIdx = boundaryIdx - sliceSize + 1;
rightIdx = boundaryIdx + sliceSize;
if leftIdx >= 1 && boundaryIdx <= size(arr,1)
A = arr( leftIdx:boundaryIdx, : );
else
A = [];
end
if boundaryIdx >= 0 && rightIdx <= size(arr, 1)
B = arr( boundaryIdx+1:rightIdx, : );
else
B = [];
end
end
Now call like this:
tapSize = 454;
[A1, B1] = GetTapBoundaries( interpolated, 1, tapSize );
[A2, B2] = GetTapBoundaries( interpolated, 2, tapSize );
% etc ...
[A12, B12] = GetTapBoundaries( interpolated, 12, tapSize );
Or you could use cell arrays:
tapSize = 454;
numTaps = floor( size(interpolated,1) / tapSize );
A = cell(numTaps,1);
B = cell(numTaps,1);
for tap = 1:numTaps
[Ax, Bx] = GetTapBoundaries( interpolated, tap, tapSize );
A(tap) = Ax;
B(tap) = Bx;
end
Apologies for any syntactic or logical errors... I just rammed this code into my browser without checking it in MATLAB.