Fraction calculation with Text
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Florian Fbr
le 14 Nov 2015
Commenté : Walter Roberson
le 15 Nov 2015
Hey guys,
i have the following arrays which are saved separately in my Workspace(See below the screenshot). Array A is called "total" in my Workspace and Array B is named "relevant"

I need a code that gives me a table with the fractions:
Number the country is mentioned in Array B / Total number the Country is mentioned in Array A.
So for example: IT appears 2 times in Array B and 7 times in Array A. The fraction is 2/7 = 0.28...
It would be really nice if the fractions are then illustrated in a table in a descending order.
So the final table should look like:

I would really appreciate your help :)
Best Florian
0 commentaires
Réponse acceptée
Walter Roberson
le 14 Nov 2015
allcountries = union(ArrayA, ArrayB);
ncountry = length(allcountries);
[tfA, idxA] = ismember(ArrayA, allcountries);
countsA = accumarray(idxA(tfA), 1, [ncountry, 1]);
[tfB, idxB] = ismember(ArrayB, allcountries);
countsB = accumarray(idxB(tfB), 1, [ncountry, 1]);
results_numeric = [countsB./countsA, countsB, countsA];
results_cell = [allcountries(:), num2cell(results_numeric)];
I included the actual counts as well as the fraction.
The code could be made a little shorter if it was certain that all the countries were represented at least once in each array. Any country which appears in Array B but not in Array A will show up with a fraction of Inf; any country which appears in Array A but not in Array B will show up with a fraction of 0.
3 commentaires
Image Analyst
le 15 Nov 2015
I see you've Accepted the answer so I assume you've got it working since you've posted the above comment. Reply back if that's not the case. If you do, give your code, especially code to generate ArrayA and ArrayB.
Walter Roberson
le 15 Nov 2015
It is not possible to have an array named "Array A" in MATLAB: spaces are not permitted in the names of variables.
Your diagram is showing Array B as a cell array of strings, but the error message is saying that the second input is a plain matrix of double. Please re-check the variables you are using. Also ensure that they only have strings in them, not a mix of strings and numbers and that none of the entries are the empty array.
Plus de réponses (1)
Image Analyst
le 14 Nov 2015
I think you can do this with grpstats() in the Statistics and Machine Learning Toolbox, but I can't try it since you didn't provide any code to generate the arrays. If you don't have that toolbox, try the brute force way with ismember(). You might also need to use unique() and cellfun().
3 commentaires
Voir également
Catégories
En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!