present decimal values in a pie graph

조회 수: 4 (최근 30일)
Nitai
Nitai 2019년 5월 3일
댓글: dpb 2021년 7월 29일
Hello, I'm struggling in a specific action in a pie graph. After I input a vector of numbers, if the sum of the numbers is bigger than 100, than the program should do the following action in a for loop.
afterwards a pie graph should be created and the numbers should be presented in their decimal value. my code works fine and creates the graph besides the decimal part. I would love to get a hand in here how to turn my values into their decimal values (I know this code won't do it, I'm not familiar with any command that would do that).
else sum(num) > 100
for i = 1 ; length(num) %for loop that takes every value, divides it by the sum of the vector and multiply by 100%
num(i) = ((num(i)/sum(num))*100);
end
pie(num);
thanks in advance.

채택된 답변

dpb
dpb 2019년 5월 3일
편집: dpb 2019년 5월 3일
...
for i = 1 ; length(num) % ";" should be ":"
num(i) = ((num(i)/sum(num))*100);
end
Use Matlab array syntax instead of loops...
num=100*num/sum(num); % Matlab is "MATrix LABoratory", use vectorized operations
pie(num,cellstr(num2str(num(:),'%05.2f%'))) % write percentages as labels
NB: the (:) on the num array to ensure is column vector in argument to num2str to ensure generates a columnar list of char strings; a row vector gets turned into one long string instead, not at all what you want.
"Salt to suit" the precision for the format string...
ADDENDUM/ERRATUM
Fixed missing cellstr() cast and mistyped format string (had 5f.2 rather than 5.2f)
  댓글 수: 4
Giuseppe Degan Di Dieco
Giuseppe Degan Di Dieco 2021년 7월 29일
Dear dpb,
thanks both for your tip and example.
Easy and clear.
Best!
dpb
dpb 2021년 7월 29일
Glad it helped...

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Pie Charts에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by