convert char to double in matlab: str2double - matlab

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)

Related

Storing the digits after the comma in Matlab

I have a double between 0 and 1 stored in an array in Matlab B.
I want to create a vector t storing the N digits after the comma. If the digits after the comma are <N, then the corresponding element in the vector t should be 0.
Suppose N=10 and B=[0.908789]. Then,
t=[9;0;8;7;8;9;0;0;0;0];
This is the code I am using at the moment
n = fix(rem(B,1)*10^N);
s1 = sprintf('%.0f',n);
ttemp = (s1-'0')';
t=zeros(N,1);
t(1:size(ttemp,1))=ttemp;
but it gives me wrong results.
Indeed, suppose
B=[7.0261e-05] and N=5. The code above gives me
t=[7;0;0;0] without recognising that there e-05.
Any suggestion on how to fix this?
You need to tell sprintf that you'd like all leading 0's to actually be shown if there are fewer than N digits:
Your current way:
sprintf('%.0f', n);
% '7'
The correct way:
s1 = sprintf('%05.f', n);
% '00007'
The general example for any N would be:
s1 = sprintf(['%0', num2str(N), '.f'],n);
The way that you currently have it written, the outpuf of the sprintf command is simply a '7' which when you fill in your output starting at the beginning yields a 7 followed by all 0's (the value you initialized the output to).
If we initialize it to NaN values instead of 0's you can see what the issue is
N = 5;
B = 7.0261e-05;
n = fix(rem(B,1)*10^N);
% 7
s1 = sprintf('%.0f',n);
% '7'
ttemp = (s1 - '0').';
% 7
t = nan(N, 1);
% NaN NaN NaN NaN NaN
t(1:size(ttemp,1)) = ttemp;
% 7 NaN NaN NaN NaN
Alternately, you can keep everything you have and just modify t from the end rather than the beginning
t = zeros(N, 1);
t((end-numel(ttemp)+1):end) = ttemp;
Unsolicited Pointers
' is not the transpose, .' is.
Use numel to determine the number of elements in a vector rather than size since it will work for both row and column vectors

Mod function returns 0 for Matlab

I have a problem with the mod function output in Matlab. I am trying to perform some calculations for ECC double and add algorithm. I am reading data from a file and storing it in a variable and then performing some operations. All works smoothly except that I get 0 in temp1 when I use mod(X2,P). However if I put in values stored in X2(3.0323e+153) and P(1.1579e+77) on command window (mod( 3.0323e+153, 1.1579e+77)), I get the correct values. Can anyone please help me? Below is the part of script which is problematic.
P = hex2dec('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F');
line = fread(fileID,[1,67],'*char');
while ~feof(fileID)
PX = line(4:67);
X = hex2dec(PX);
X2 = X^2;
temp1= mod(X2 , P)
end
line = fread(fileID,[1,69],'*char');
end
fclose(fileID);
I think the problem lies with how you're initializing P. From the documentation for hex2dec (emphasis mine):
d = hex2dec('hex_value') converts hex_value to its floating-point integer representation. The argument hex_value is a hexadecimal integer stored as text. If the value of hex_value is greater than the hexadecimal equivalent of the value returned by flintmax, then hex2dec might not return an exact conversion.
And the value of flintmax is:
>> flintmax
ans =
9.007199254740992e+15
Quite a bit smaller than your value for P. In fact, if we use num2hex to look at the two ways you initialize P, you can see a clear difference:
>> P = hex2dec('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F');
>> num2hex(P)
ans =
4ff0000000000000
>> num2hex(1.1579e+77)
ans =
4fefffda293c30de
As it turns out, the inexact conversion done by hex2dec results in a number that evenly divides into 3.0323e+153, thus giving you a remainder of 0:
>> mod(3.0323e+153, P)
ans =
0
>> mod(3.0323e+153, 1.1579e+77)
ans =
8.795697942083107e+76

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';

Saving and comparing rounded numbers for MATLAB

So i'm creating a function that is trying to compare decimal numbers with scientific notation. I am trying to round them off and saving them into new variables.
What I did is this...
>> digits(3);
>> Y = vpa(0.000036856864)
Y =
3.69e-5
>> Z = vpa(0.000036857009)
Z =
3.69e-5
>> eq(Y,Z)
ans =
0
Technically the new rounded decimal is saved unto Y and Z, so when I compare the two variables, it gives me 0, but it should be 1. How can I fix this to make sure that the answer equals to 1?
Any help is appreciated!
The values returned by vpa aren't actual numbers - they're symbolic objects that still contain the original value of the number (before rounding). To compare the two, you should convert them back to double:
Y = double(vpa(0.000036856864))
Z = double(vpa(0.000036857009))
eq(Y,Z)
which should return 1

Matlab: Cell column with mixed char/double entries - how to make all numerical?

I'm importing large datasets into Matlab from different Excel files. I use [~,~,raw] = xlsread('myfile.xlsx') to obtain a raw input into a single Matlab cell.
One column consists of interest rates, and the entries are imported as either CHAR (if they're decimal numbers) or DOUBLE (if they're rounded to integers).
Now, I want to slice out that column and get a numerical vector, which Matlab doesn't like. If i use str2num, all the CHAR entries are converted into DOUBLE, but the DOUBLES becomes NaN. Is there a function/solution to take into account that some entries are already DOUBLE?
You can probably work this into your existing code rather than create a whole new function but this should work for you. The functions not vectorized though but since it a cell vector I don't think that's an issue
function number = str2numThatHandelsNumericInputs(obj)
if isnumeric(obj)
number = obj;
else
number = str2num(obj);
end
end
Or as Eitan points out a better function:
function num = str2numThatHandelsNumericInputs(num)
if ischar(num)
num = str2num(num);
end
end
I think I didn't quite understand your question, because I understood you have something like this:
raw = {...
'1.2345' , NaN
3 , inf
4 , #cos
'567.1232' , { struct }
};
In which case you could just use str2double:
>> inds = cellfun('isclass', raw(:,1), 'char'); % indices to non-numeric data
>> raw(inds,1) = num2cell(str2double(raw(inds,1))); % convert in-place
>> [raw{:,1}].' % extract numeric array
ans =
1.2345
3.0000
4.0000
567.1232
But is this what you mean?