How to Convert a Vector to a Number in Matlab? - matlab

I have a vector, A=[2 2 4 5]. I want to convert A to a number. Answer should be 2245.
Example 2. B=[5,6,7,8,9]. Answer should be 56789.
Thanks.
PS. Thanks to all. Now I understand to convert the vector to a string and delete the space, and convert back to a number.

You could try this -
>> a = [2 3 10];
>> str2num(strrep(num2str(a), ' ', ''))
ans =
2310
Why does it work? Well, num2str ("number to string") converts the vector into its character representation
>> num2str(a)
ans =
2 3 10
which is almost what you want, except for the spaces between the numbers. So you call strrep ("string replace") to replace all the spaces (' ') with the empty string ('')
>> strrep('hi there', ' ', '')
ans =
hithere
and finally use str2num ("string to number") to convert the resulting string back into a number.

Take each number, convert it to a string and concatenate the results. Take this string and convert it back into a number. You can use num2str on the array, remove any white spaces that result from this conversion using ismember then convert the string back to a number with num2str:
C = [2 3 10];
strC = num2str(C);
strC(ismember(strC, ' ')) = [];
out = str2num(strC)
out =
2310
Alternatively, you can use strrep to replace all spaces with nothing after you run num2str, then convert back to a number:
C = [2 3 10];
strC = num2str(C);
strC = strrep(strC, ' ', '');
out = str2num(strC)
out =
2310
Tipping the hat to Chris Taylor, this can all be done in one line:
out = str2num(strrep(num2str(C), ' ', ''))
out =
2310
One more for academic purposes is to use regular expressions. Specifically, use regexprep on the converted string array that is output from num2str and replace all spaces with nothing:
C = [2 3 10];
strC = num2str(C);
out = str2num(regexprep(strC, '\s*', ''))
out =
2310
The pattern \s* searches for 0 or more white space characters. We find these and set them to nothing.

Thanks to #obchardon for a correction.
This uses only arithmetics (no strings). It works for numbers greater than 0. A can be a row or column vector.
A = [2 0 3 10];
x = cumsum(floor(log10(A.'+(A.'==0)))+1);
x = x(end)-x;
result = A(:).'*10.^x
which gives
result =
20310

If you want to string all of the digits together like they are the digits in a single integer you can convert the vector to a string, remove the spaces to smoosh the digits together, and then convert it back to a single number.
This way will handle an arbitrary number of digits in each vector element (assuming they are all real integers) rather than trying to multiply each element by the respective power of 10 and taking the sum.
Example code:
A = [2 44 12 6];
Astr = num2str(A);
Astr(strfind(Astr, ' ')) = [];
Anum = str2double(Astr);

This uses num2str without having to worry about whitespaces.
Apply num2str to every number using arrayfun, concatenate the resulting strings, convert back to number. Sadly it is quite a bit slower than the whitespace-deleting or numerical approach.
numStrings = arrayfun(#num2str,a,'uni',0);
out = str2num(cat(2,numStrings{:}))
out =
2310

Related

Adding each element in a vector yields no number

I have a vector,
a2 = [8 10 18 18]
I want to add all individual digits in this vector, i.e.
8 + 1+0 + 1+8 + 1+8 = 27
I decided to use the following piece of code:
a3 = num2str(a2)
sum2 = 0;
for k = 1:numel(a3)
sum2 = sum2 + str2num(a3(k));
end
sum2
However, when I output this I get sum2 = []. What exactly is going wrong here? Apparently, a3 has 13 elements, which means the spaces must be 2 elements wide. Does the issue lie there?
Recommended Solution:
Use num2str, cellstr, str2double, and sum with the omitnan flag.
req = num2str(a2);
req = sum(str2double(cellstr(req(:))),'omitnan');
num2str converts the given matrix a2 into a character array. req(:) reshapes the character array req into a column vector. It still contains spaces. cellstr is applied to convert the column character array into a cell array so that str2double can be applied. str2double converts the spaces into NaN and the char numbers into respective doubles. sum with the omitnan flag ignores the NaN while addition.
Just another Solution:
It can also be done using just num2str, str2num, and sum. But str2num uses eval and hence it should be avoided. Anyhow just for the fun of it:
req = num2str(a2);
req = sum(str2num(req(:)));
Just like the previous solution, when str2num is applied on the column character array containing spaces, spaces get removed and the remaining char numbers are converted into respective doubles. The operation of the sum function is obvious.
Why does your code not work?
When str2num is applied on the space character, [] is returned. When [] is added into any number, the result is also []. Since in your code a3 contains spaces, hence you get [] as output.
You can exploit the ASCII mapping:
b = uint64(num2str(a2') - '0')
b =
4×2 uint64 matrix
0 8
1 0
1 8
1 8
and then sum:
sum(b(:))
ans =
27
Just for fun, a shorter, faster, less robust and less readable solution:
sum2 = sum(sprintf('%d',a2)-'0');
Breakdown:
sprintf to convert all elements of a2 to a string without space as delimiter, like num2str would do
subtracting '0' implicitly casts the character array to the ASCII code equivalents. Subtracting the ASCII value for 0 then results in numbers 0-10
sum() to complete the operation.
Note that if a2 was a string to begin with, this solution will not give an error (same for the other answer, by the way)

how to convert char to number in matlab?

Please help me with the following problem:
In matlab, I have an Nx3 char variable, where N can vary depending on the input.
Let's say N = 5 and I have the following variable A (5x3 char):
A = [' 1Y';
' 5Y';
'10Y';
'15Y';
'20Y']
Is there a way to define a new variable B having as values the numbers in variable A, i.e. B=[1; 5; 10; 15; 20]?
Thank you for your help!
Since your input is a character array, first convert each row into a cell to allow use with the string functions in MATLAB:
out = mat2cell(val, ones(size(val,1),1));
mat2cell converts a matrix into a series of cells. In our case, you would like to have 5 cells, or as many cells as there are rows in your matrix val and each cell will be as long as the total number of column in val.
Once you do this, you can replace the Y strings with nothing, then convert to numbers:
out = strrep(out, 'Y', '');
out2 = cellfun(#str2num, out);
The first line uses strrep to replace any instances of Y with nothing, and then we apply str2num on each of the cells to convert the trimmed string into an actual number. This is through the use of cellfun so that we can iterate through each cell apply str2num to each cell.
We get:
out2 =
1
5
10
15
20
To be fully reproducible:
val = ['1Y '; '5Y '; '10Y'; '15Y'; '20Y'];
out = mat2cell(val, ones(size(val,1),1), size(val,2));
out = strrep(out, 'Y', '');
out2 = cellfun(#str2num, out);
Suppose you have the following:
A = [' 1Y';
' 5Y';
'10Y';
'15Y';
'20Y';]
Then this should do the trick:
B=A'
C=strsplit(B(:)','Y')
V=cellfun(#str2num,C(1:end-1))
This is how you can convert a cellstr to its numeric value:
a = {'1'};
ans1 = int64(str2num(a{1}));

How to convert a String to a Matrix Matlab

Im trying to convert a String into a Matrix. So like a=1 b=2... "Space"=28. Etc.
My question is how would I convert a string to a matrix?
aka..
abc=[1,2,3]
Tried a for loop, which does convert the string into numbers.
Here is where I try to make it into a Matrix
String1=char(string)
String2=reshape(String1,[10,14]);
the error I get is
"To RESHAPE the number of elements must not change"
"String2=reshape(String1,[10,14]);
If you need a general coding from characters into numbers (not necessarily ASCII):
Define the coding by means of a string, such that the character that appears first corresponds to number 1, etc.
Use ismember to do the "reverse indexing" operation.
Code:
coding = 'abcdefghijklmnñopqrstuvwxyz .,;'; %// define coding: 'a' is 1, 'b' is 2 etc
str = 'abc xyz'; %// example text
[~, result] = ismember(str, coding);
In this example,
result =
1 2 3 28 25 26 27

Char array to numeric array in matlab

I have the following matrix A of size 3x2:
A = [12; 34; 56];
But the data is stored as chars. I want to convert it to the numeric array. str2num doesn't. Is there another method to do that?
Well, your array doesn't look like a 3-by-2 array. In any case, you are looking for a casting function:
A = double(A);
should convert your chars in double.
If I understand correctly, you have
A = ['12'; '34'; '56']; %// strings
and want to get
B = [1 2; 3 4; 5 6]; %// numbers
This could be done as follows: convert A to double to produce each character's ASCII code, and then subtract the code of character '0' to obtain the desired numbers. In fact, conversion to double is done implicitly when you subtract chars, so you can just use
B = A-'0';

how to sum digits in a multi-digit number Matlab

I wonder how to sum digits for a multi-digit number in Matlab.
For example 1241= 1+2+4+1 = 8
String-based answer:
>> n = 1241;
>> sum(int2str(n)-48)
ans =
8
The number is first converted to a string representation using int2str, then the ASCII code for '0' (i.e. 48) is subtracted from the ASCII code for each element of the string, producing a numeric vector. This is then summed to get the result.
A = 35356536576821;
A = abs(A);
xp = ceil(log10(A)):-1:1;
while ~isscalar(xp)
A = sum(fix(mod(A,10.^xp)./10.^[xp(2:end) 0]));
xp = ceil(log10(A)):-1:1;
end
this is the numeric approach
This one is the solution is character approach:
A = '35356536576821';
A = char(regexp(A,'\d+','match'));
while ~isscalar(A)
A = num2str(sum(A - '0'));
end
Both, first take the absolute number (strip the minus) then: the numeric one counts with log10() how many digits a number has and through modulus and divisions extracts the digits which are summed, while the char approach convert to numeric digits with implicit conversion of - '0', sums and converts back to string again.
Another all-arithmetic approach:
n = 1241; %// input
s = 0; %// initiallize output
while n>0 %// while there is some digit left
s = s + mod(n-1,10)+1; %// sum rightmost digit
n = floor(n/10); %// remove that digit
end
Youcan use this code
sum(int2str(n)-48)
where n, is your input number.