How can I index one array using element values from another array

4 views (last 30 days)
My aim is to obtain a sum of total spending for specific age groups (20s, 30s, 40s etc) by combining data from two excel spreadsheets.
I have managed to create two arrays from these spreadsheets. One consists of the total spending for each customer (customer_spend). For this one, the row-number is the customer id. The other is an array of customer ids sorted into age groups.
I am struggling to combine the two to find the total sum of spending per age group.
The first 4 lines are extracting data from excel spreadsheets in my workspace. The reason there is an 'x' and 'x1' which both represent customer ids is that the spreadsheets have different numbers of data ids in each.
x = table2array(transactions(:,3)); %customer id (transactions)
x1 = table2array(demographic(:,1)); %customer id (demographic)
y = table2array(transactions(:,11)); %cost
z = table2array(demographic(:,6)); %age
%%% assigning total spend to each customer id %%%
[xnew,~,idx] = unique(x); %combines customer ids so there are only 1 of each
customer_spend = accumarray(idx(:),y(:)) %sum of customer cost in an array
%%% sorting customer ids into age groups %%%
subthirty = x1(z < 30);
thirtis = x1((z>29) & (z<40));
fortis = x1((z>39) & (z<50));
fiftis = x1((z>49) & (z<60));
sixtyplus = x1((z>59) & (z<100));
Thank you

Accepted Answer

Sulaymon Eshkabilov
Sulaymon Eshkabilov on 9 Aug 2020
Hi,
Again using logical indexing might be one of the easy ways of doing it:
Y_sub30 = y(z < 30); Total_sub30=sum(Y_sub30);
Y_30 = y(z > 29 & z<40); Total_30=sum(Y_sub30);
Y_40 = y(z > 39 & z<50); Total_30=sum(Y_sub40);
%...
% etc.
%% Or directly
Total_sub30=sum(y(z < 30));
Total_30=sum(y(z > 29 & z<40));
Total_40=sum(y(z > 39 & z<50));
% etc..
Good luck

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!