MATLAB: Extract values from double with for loop and calculate sum

additioncellfor loopindexing

Dear matlab-ers!
I have a double, called 'file' here, consisting of two columns and 36 rows. In the second column I have values from 0-17 randomly distributed and not occuring the same number of times. In the first column there is a 0 or 1 assigned to every value in the second column. I now want to look at every value in the second column from 0-17 and separately, for each occurence of that number, sum the respective value in column 1. Later I want to calculate the mean of each sum.
Say the value 5 occurs 4 times in column 2 and in column 1 the respective values are 1,1,0,1.
I'm not sure how to extract the numbers, what strcuture to put the numbers into and how to add them up.
This is a fraction of my code. I hope I could get my idea across and hope you can help me. I appreciate any tips!
An unexperienced beginner.
number = 0:17; %18 different values in column 2
row = 1:36; %36 rows
C = cell(20,17); %
for i = number
for ii = row
if file(ii,2) == i; %looking at 0-17, if number found, extract value in same row of first column
C{i} = C{i} + file(ii,1); %trying to add up the values
end
%... adjust counters after loop

Best Answer

There's no need for loops. I'll walk you through my solution.
I have a double, called 'file' here, consisting of two columns and 36 rows. In the second column I have values from 0-17 randomly distributed and not occuring the same number of times. In the first column there is a 0 or 1 assigned to every value in the second column.
%Generate data based on description
file = [randi(2, 36, 1)-1, randi(18, 36, 1)-1];
I now want to look at every value in the second column from 0-17 and separately, for each occurence of that number, sum the respective value in column 1.
% Create groups based on the 2nd column of 'file'
[group, groupID] = findgroups(file(:,2));
% apply the "SUM" function to column 1 of 'file' within each group defined in column 2.
groupSum = splitapply(@sum, file(:,1), group);
% Display the results in a table
table(groupID, groupSum)
Later I want to calculate the mean of each sum.
I'm not sure what this means. The mean of a single number is just that single number. However, you can replace the "SUM" function with any other function. Here are some examples.
% Calculate the mean of column 1 within each group
groupSum = splitapply(@mean, file(:,1), group);
% Determine the number of members of each group
groupSum = splitapply(@length, file(:,1), group);
% apply a more advanced function where I take the sum and multiply by 3
groupSum = splitapply(@(x) sum(x)/3, file(:,1), group);