MATLAB: Having trouble finding the mean of array elements between two indices

cell arraymatrixmean

I'm getting a math error in a script I'm writing and haven't been able to figure out the problem. I'm trying to use a loop to calculate the mean of a group of array elements from one specific index to another.
totalReps = totalReps(~cellfun('isempty', totalReps'));
for i = 1:length(totalReps)
A = cell2mat(totalReps(i));
nzer(end + 1) = length(find(A));
end
repMeans = zeros(1, length(totalReps), 'single');
for i = 1:length(totalReps)
for j = int16(nzer(i) * 0.25):int16(nzer(i) * 0.75)
repMeans(i) = repMeans(i) + totalReps{i,1}(1,j);
end
repMeans(i) = repMeans(i) / (nzer(i) * 0.5);
end
totalReps is a N x 1 cell array composed of differently-sized 1 x N single-precision arrays. The purpose of this part of the script was to find the average of the middle 50% of the nonzero values in each element of totalReps. Every element of totalReps is some number of nonzero values followed by a number of zero values, so I used find() to create a parallel array nzer in order to index the nonzero elements. I then used a double for loop to add the middle 50% of each element into another parallel array repMeans. However after running the script, the elements of repMeans appear to all be off by around 1. If they are off by exactly 1 then it's easy enough to fix, but I'd like to understand what's going on.
I attached .xlsx files representing sample totalReps and corresponding repMean values.
Thanks in advance.

Best Answer

See my comments to the question.
Using a matrix, and assuming you're using R2019b since you haven't indicated a matlab version:
totalreps = readmatrix('totalReps.xlsx'); %read the lot as a matrix
totalreps = fillmissing(totalreps, 'constant', 0); %replace the NaNs by 0 since it makes no difference
repMeans = zeros(size(totalreps, 1), 1); %create a COLUMN vector since we're working on rows. You can make it 'single' if you wish.
for row = 1:size(totalreps, 1);
validcount = nnz(totalreps(row, :));
repMeans = mean(totalreps(row, round(validcount * 0.25) : round(validcount * 0.75)));
end