Extract values from double with for loop and calculate sum
Afficher commentaires plus anciens
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
Réponse acceptée
Plus de réponses (1)
TADA
le 7 Fév 2019
Can also use accumarray to solve this one
n = 10;
xMax = 7;
% generate the matrix as: [boolean, x, 1]
% x is the column of values you wanted (between 0 and xMax)
% boolean is the flag 0/1
% the third column will be used to count the occurences of each value to
% calculate the mean boolean value of each
file = [randi(2, n, 1)-1, randi(xMax, n, 1), ones(n, 1)];
% turn x column into a list of valid subscripts
idx = file(:,2)+1;
accumulatedFlags = accumarray(idx, file(:,1));
nOccurences = accumarray(idx, file(:,3));
uniqueValues = unique(file(:,2));
uniqueIdx = uniqueValues+1;
% [sum, x, mean]
out = [accumulatedFlags(uniqueIdx), uniqueValues, accumulatedFlags(uniqueIdx)./nOccurences(uniqueIdx)];
1 commentaire
Pauli
le 8 Fév 2019
Catégories
En savoir plus sur Tables dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!