MATLAB Answers

# Error in splitapply command

52 views (last 30 days)
Ivan Mich on 27 Feb 2021
Commented: Image Analyst on 28 Feb 2021
I am using this command "splitapply" in order to find mean (average) of a group of data.
edges=1:0.5:10
[N, edges, bin] = histcounts(B, edges);
mean_B=splitapply(@mean, B, bin) %mean
%B is 1000x1 double
But command window shows me :
Error using splitapply (line 61)
Group numbers must be a vector of positive integers, and cannot be a sparse vector.
which is curiousness because for an another set of data code runs.
Could you please help me?
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Answers (1)

Image Analyst on 27 Feb 2021
This seems to work fine:
B = 1 + 9 * rand(1, 100000);
edges = 1 : 0.5 : 10
[counts, edges, bin] = histcounts(B, edges);
% bin says what bin the value was placed into.
% Compute the means of the values in each bin.
mean_B = splitapply(@mean, B, bin)
Attach your B so we can see why it's different than mine. If your B exceeds 10, it will say that bin is zero for those values exceeding 10, and that would be a problem since you're passing in bin as the "group number" and the group numbers have to be natural numbers (1,2,3,4,...) and not zero.
##### 13 CommentsShowHide 12 older comments
Image Analyst on 28 Feb 2021
Keep in mind that you can't delete/remove elements from a array with more than 2 dimensions because it must remain rectangular. It can't have "holes" or "ragged edges" in it. You can only remove elements from a 1-D vector.
If you have a 2-D matrix and get a map of where it's above or below some threshold, then if you pass that into the 2-D matrix as a logical index, it can't give you a 2-D matrix back with "holes" in it where the non-selected elements are missing. So it returns the elements all concatenated in a 1-D vector pulled from the original matrix in a "column major" manner.

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!

Translated by