Converting columns in a matrix to percentage
6 views (last 30 days)
Show older comments
Sophie Stringer
on 7 Sep 2019
Commented: Sophie Stringer
on 7 Sep 2019
Hi there,
I have a data file that I would like to convert to percentage. It looks like this and is called nMJO.
48 40 35 52 38 11 64 39 26
50 35 37 55 43 24 54 25 26
33 27 36 28 26 27 39 27 16
40 29 40 51 29 24 47 32 29
66 37 38 51 41 16 52 29 24
62 41 37 48 40 17 41 23 24
57 26 33 46 29 8 37 21 24
63 39 22 47 45 11 38 25 17
I would like to convert each column to equal 100% and then for each value in every column, work out its percentage for that column. I would preferablly like to do this in a loop, and create a new matrix of percentages, that I can then plot as a stacked bar plots.
the code I've come up for so far is.
for i=1:9
MJO_sum = sum(nMJO == i)
for MJO_node_ind = 1:8
nMJO_percent(MJO_node_ind, i) = nMJO/MJO_sum(:,i)
end
end
0 Comments
Accepted Answer
Stephen23
on 7 Sep 2019
Edited: Stephen23
on 7 Sep 2019
>> M = [48,40,35,52,38,11,64,39,26;50,35,37,55,43,24,54,25,26;33,27,36,28,26,27,39,27,16;40,29,40,51,29,24,47,32,29;66,37,38,51,41,16,52,29,24;62,41,37,48,40,17,41,23,24;57,26,33,46,29,8,37,21,24;63,39,22,47,45,11,38,25,17]
M =
48 40 35 52 38 11 64 39 26
50 35 37 55 43 24 54 25 26
33 27 36 28 26 27 39 27 16
40 29 40 51 29 24 47 32 29
66 37 38 51 41 16 52 29 24
62 41 37 48 40 17 41 23 24
57 26 33 46 29 8 37 21 24
63 39 22 47 45 11 38 25 17
>> P = 100*bsxfun(@rdivide,M,sum(M,1))
P =
11.4558 14.5985 12.5899 13.7566 13.0584 7.9710 17.2043 17.6471 13.9785
11.9332 12.7737 13.3094 14.5503 14.7766 17.3913 14.5161 11.3122 13.9785
7.8759 9.8540 12.9496 7.4074 8.9347 19.5652 10.4839 12.2172 8.6022
9.5465 10.5839 14.3885 13.4921 9.9656 17.3913 12.6344 14.4796 15.5914
15.7518 13.5036 13.6691 13.4921 14.0893 11.5942 13.9785 13.1222 12.9032
14.7971 14.9635 13.3094 12.6984 13.7457 12.3188 11.0215 10.4072 12.9032
13.6038 9.4891 11.8705 12.1693 9.9656 5.7971 9.9462 9.5023 12.9032
15.0358 14.2336 7.9137 12.4339 15.4639 7.9710 10.2151 11.3122 9.1398
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!