How to calculate the number from a database

조회 수: 1 (최근 30일)
Kaijia Chen
Kaijia Chen 2021년 11월 30일
댓글: Akira Agata 2021년 12월 8일
I have a struct which records 10 TV, in each struct the film's countries are provided.
There're 3 different countries(US, CN, CA) in the struct. I need to determine the total amount of TV shot by each countries.
I tried to use this function, but it only works for a single country, when the I add more than one country, the total number is inaccurate.
function [countries, count] = movies_countries(films)
count = ['US';'CA';'CN'];
US = [];CA = [];CN = [];
countries = [];
for ii = 1:length(TV)
if ~isempty(strfind(upper(TV(ii).country),'US'))
US(end+1) = ii;
A1 = size(US);
B1 = A1(1,2);
if ~isempty(strfind(upper(TV(ii).country),'CA'))
CA(end+1) = ii;
A2 = size(CA);
B2 = A2(1,2);
if ~isempty(strfind(upper(films(ii).country),'CN'))
FR(end+1) = ii;
A3 = size(CN);
B3 = A3(1,2);
countries = [B1 B2 B3]
end
end
end
This is the database:
TV(1).country = 'US';
TV(2).country = 'US';
TV(3).country = 'CN';
TV(4).country = 'CN';
TV(5).country = 'CA';
TV(6).country = 'US';
TV(7).country = 'CN';
TV(8).country = 'CN';
TV(9).country = 'US';
TV(10).country = 'US'
The final output should looks like:
countries = 'US'; 'CN';'CA'
count = 5 4 1
  댓글 수: 5
Kaijia Chen
Kaijia Chen 2021년 11월 30일
Sure!
This is the expected output
>>[countries count] = movies_by_countries(films)
countries =
3×2 char array
'US'
'CN'
'CA'
count =
5 4 1
Kaijia Chen
Kaijia Chen 2021년 11월 30일
And the TV is just a 1×10 struct array.

댓글을 달려면 로그인하십시오.

채택된 답변

Akira Agata
Akira Agata 2021년 11월 30일
How about the following?
List = arrayfun(@(x) x.country, TV,...
'UniformOutput', false);
[Group, Country] = findgroups(List');
Count = accumarray(Group,1);
>> Country
Country =
3×1 cell array
{'CA'}
{'CN'}
{'US'}
>> Count
Count =
1
4
5
  댓글 수: 3
Kaijia Chen
Kaijia Chen 2021년 11월 30일
Hi, what if there exists a film produces more than one country.
For example if
So your equation produces
But I don't want {'US' 'CN'}, I want three catagory {'CA'} {'CN'} {'US'}
Akira Agata
Akira Agata 2021년 12월 8일
I believe the following will work for such case:
List = arrayfun(@(x) x.country, TV,...
'UniformOutput', false);
List2 = cellfun(@(x) split(x,'''')', List,...
'UniformOutput', false);
List2 = [List2{:}];
[Group, Country] = findgroups(List2');
Count = accumarray(Group,1);

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Interactive Model Editing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by