convert number in a matrix to a scalar
Show older comments
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 Comments
Stephen23
on 12 Jun 2018
@Reema Alhassan: please upload your data matrix in a .mat file, by clicking the paperclip button.
Reema Alhassan
on 12 Jun 2018
@Reema Alhassan: in your uploaded Mfile you use sprintf to convert the maximum values into a char vector. But then confusingly there is a comment which states "i need the sumOfValues to be a scalar (double)": if you want sumOfValues to be a scalar double, why are you using sprintf to convert that scalar numeric to a character vector?
Reema Alhassan
on 12 Jun 2018
Edited: Walter Roberson
on 12 Jun 2018
Stephen23
on 12 Jun 2018
@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.
Accepted Answer
More Answers (1)
Ameer Hamza
on 12 Jun 2018
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 Comments
Walter Roberson
on 12 Jun 2018
A matrix of results would have been returned if you had forgotten the (:) -- if you had used sum(values) for example.
Ameer Hamza
on 12 Jun 2018
@Reema In MATLAB a 1x1 matrix is a scalar. There is no separate class type scalar in MATLAB.
Ameer Hamza
on 12 Jun 2018
Can you give an example of what is not working. Because the syntax is fine. Except if you forget (:) as pointed by Walter.
@Reema Alhassan: It sounds like a misunderstanding. 1x1 matrices are scalars in Matlab. There is no difference:
a = 5
size(a)
% [1 1]
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!