convert number in a matrix to a scalar
조회 수: 124 (최근 30일)
이전 댓글 표시
Hello everyone I have matrix "values" and I need to sum all of it's element so I use sumOFvalues= sum(values(:)); the sumOFvalues is a matrix and I need to convert it into a scalar so I can addit with any number independent of the size. does any one know how to do this ?
thanks
댓글 수: 5
Stephen23
2018년 6월 12일
@Reema Alhassan: numeric data types do not store any formatting information. How any numeric looks is irrelevant to how it is stored in memory. Converting your scalar numeric to a char vector is not likely to help you.
채택된 답변
Walter Roberson
2018년 6월 12일
The bug is your line
sumOfValues=sprintf('%f', sumOfValues);
sprintf() formats numeric values as character vectors and returns the character vector. The output of the sprintf() is not a number: it is a character vector. In your case it happens to be a character vector containing 15 characters, '10765655.982710', which is the vector ['1' '0' '7' '6' etc] .
You are then writing over your original numeric value with that character vector.
What was your intent in using sprintf() at that point in your code?
댓글 수: 3
Walter Roberson
2018년 6월 12일
At the MATLAB command line give the command
format long g
and then display the numeric value again.
추가 답변 (1개)
Ameer Hamza
2018년 6월 12일
What you are doing is correct, it should return a scalar value. For example
values = randi(5, 3, 3)
values =
2 4 1
4 1 1
1 2 5
sumOfValues = sum(values(:))
sumOfValues =
21
댓글 수: 4
Ameer Hamza
2018년 6월 12일
Can you give an example of what is not working. Because the syntax is fine. Except if you forget (:) as pointed by Walter.
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!