How convert integer matrix to specific String in matlab - matlab

For example, I have this Matrix:
a=[100,20,3,2000]
I want to save every integer in 4 places in string. However the last integer matrix will be
s='0100002000032000'

s = ''
for i = 1:size(a, 2)
s = [s sprintf('%04d', a(i))]
end
Or, even simpler, do:
s = num2str(a, '%04d')

Related

convert char to double in matlab: str2double

X= 1:63;
n = 6;
% Y = int2bit(X,n)
y=dec2bin(X, n)
with this example I tried str2double(y) and got NaN
What is a problem?
str2double will only convert text that represents real or complex scalar values. Where y is a char array of binary values. It is basically interpreting y as one large integer. Hence, it will return NaN or Inf depending on the version of MATLAB you are using.
You can use convertCharsToStrings and then use str2double
e.g
for i = 1:length(y)
tempvar = convertCharsToStrings(y(i,:));
x1(i) = str2double(tempvar);
end
OR if you just want to convert all string into double then use
arrayfun(#(x)str2double(convertCharsToStrings(x)),y,'Uniformoutput',false)

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 Vector to a Number in 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

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.

Search for a specific digit in an integer

I'm looking for a really quick method in MATLAB of searching for a specific digit within an integer, ideally in a given position. For example:
Simple case...
I want to look through an array of integers and return all those which contain the number 1 eg 1234, 4321, 6515, 847251737 etc
More complex case...
I want to loop through an array of integers and return all those which contain the number 1 in the third digit eg 6218473, 541846, 3115473 BUT 175846 would not be returned.
Any thoughts?
There's a few answers here already, I'll throw my try into the pot.
Conversion to string can be expensive, so if it can be avoided, it should be.
n = 1:100000; % sample numbers
m = 3; % digit to check
x = 1; % number to find
% Length of the numbers in digits
num_length = floor(log10(abs(n)))+1;
% digit (from the left) to check
num_place = num_length-m;
% get the digit
digit_in_place = mod(floor(abs(n)./(10.^num_place)),10);
found_number = n(digit_in_place==x);
By casting to strings, the trick to vectorising is just to make sure x is a column vector. x(:) guarantees this. Also you need to left-align the strings which is done with the format specifier '%-d' where - is for left-alignment and d is for integers:
s = num2str(x(:), '%-d');
ind = s(:,3)=='1'
and this also allows you to easily solve your first case:
ind = any(s=='1',2)
in either case to recover your original number just go:
x(ind)
One way of getting there is to cast your numbers as strings and then check if the 3rd position of that string is '1'. It works perfectly fine in a loop, but I am confident that there is also a vectorized solution:
numbers = [6218473, 541846, 3115473, 175846]'
returned_numbers = [];
for i = 1:length(numbers)
number = numbers(i);
y = sprintf('%d', number) %// cast to string
%// add number to list, if its third character is 11
if strcmp(y(3), '1')
returned_numbers = [returned_numbers, number];
end
end
% // it returns:
returned_numbers =
6218473 541846 3115473
Code
%// Input array
array1 = [-94341 1234 4321 6515 847251737 6218473 541846 3115473 175846]
N = numel(array1); %// number of elements in input array
digits_sep = num2str(array1(:))-'0'; %//' Seperate the digits into a matrix
%// Simple case
output1 = array1(any(digits_sep==1,2))
%// More complex case output
col_num = 3;
%// Get column numbers for each row of the digits matrix and thus
%// the actual linear index corresponding to 3rd digit for each input element
ind1 =sub2ind(size(digits_sep),1:N,...
size(digits_sep,2)-floor(log10(abs(array1))-col_num+1));
%// Select the third digits, check which ones have `1` and use them to logically
%// index into input array to get the output
output2 = array1(digits_sep(ind1)==1)
Code run -
array1 =
-94341 1234 4321 6515 847251737 6218473 541846 3115473 175846
output1 =
-94341 1234 4321 6515 847251737 6218473 541846 3115473 175846
output2 =
6515 6218473 541846 3115473