convert number in a matrix to a scalar

85 ビュー (過去 30 日間)
Reema Alhassan
Reema Alhassan 2018 年 6 月 12 日
コメント済み: Reema Alhassan 2018 年 6 月 12 日
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 件のコメント
Reema Alhassan
Reema Alhassan 2018 年 6 月 12 日
編集済み: Walter Roberson 2018 年 6 月 12 日
sorry I didn't realized that
I used spring if to change the number format I need it to be in a decimal form for example 15565667.224455
not like this 233+e
Stephen23
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
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
Walter Roberson 2018 年 6 月 12 日
At the MATLAB command line give the command
format long g
and then display the numeric value again.
Reema Alhassan
Reema Alhassan 2018 年 6 月 12 日
thank you!

サインインしてコメントする。

その他の回答 (1 件)

Ameer Hamza
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
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.
Jan
Jan 2018 年 6 月 12 日
編集済み: Jan 2018 年 6 月 12 日
@Reema Alhassan: It sounds like a misunderstanding. 1x1 matrices are scalars in Matlab. There is no difference:
a = 5
size(a)
% [1 1]

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by