Convert Nx1 matrix into a single number
Show older comments
Hello
I need to convert many Nx1 matrices into simple intergers. Example:
A=[1 2 3 4 5];
And what I need:
B=12345;
It isn't a problem to make it manually with small matrices, but mines are bigger than 100x1. Can someone help me?
1 Comment
"I need to convert many Nx1 matrices into simple intergers. ...but mines are bigger than 100x1"
>> intmax('uint64')
ans = 18446744073709551615
which has exactly 20 digits. If you want to store more than twenty digits, then you cannot use simple integers: you could use character vectors, symbolic integers, or use a special class, e.g.:
Accepted Answer
More Answers (2)
Max Murphy
on 3 Jan 2020
A=[1 2 3 4 5];
B=str2double(sprintf('%g',A));
4 Comments
Krzysztof Mazur
on 3 Jan 2020
Max Murphy
on 3 Jan 2020
Thanks! But I think Stephen raises a good point- I missed that you might have more than 100 digits, in which case my answer would cause an overflow.
Note that this is limited to 16 digits or so, otherwise you will lose information:
>> A = randi(9,1,17)
A =
3 6 5 4 8 6 5 9 3 7 7 4 6 1 1 5 8
>> B = str2double(sprintf('%g',A))
B =
3.654865937746116e+16
>> fprintf('%.0f\n',B)
36548659377461160
>> fprintf('%lu\n',B)
36548659377461160
Also note that the question specified up to 100 digits. There is no way to make this answer work keeping all 100 digits of information.
Produce an input vector of 100 single digits
A = randi(9,1,100); % 100 random integers 1:9
% Example: [5 9 2 9 4 5 ... ]
Convert to a character array of 100 characters without spaces
Achar = regexprep(num2str(A),' *','')
% Example: '592945725863239255999239175....'
Or, convert to a large integer
Adouble = str2double(regexprep(num2str(A),' *',''))
% Example: format long; 5.929457258632392e+99
1 Comment
Krzysztof Mazur
on 3 Jan 2020
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!