I'm using the diff Matlab function to get the difference between two successive values. And as shown here in this vector nz in this link as shown in nz the difference between col 261 and 260 is -1342 but when I use this script the result of difference between this coloumns don't appear in the result dnz. So if anyone could advise why this is not working?
This is my attempt:
load('nz.mat');
dnz = diff(nz);
If you type class(nz) you see that your data is unit16. And MATLAB saturates the results when dealing with integer values, i.e. since 0 - 1342 is lower than zero (the smallest value in uint16) it returns zero:
>> dnz=diff(nz);
>> dnz(260)
ans =
0
If you convert it to a class that can accomodate -1342 like int16 you get
>> dnz = diff(int16(nz));
>> dnz(260)
ans =
-1342
Related
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
Is there a way to convert a decimal number between $0$ and $1$ that is not integer to base 4 in Matlab? E.g. if I put 2/5 I want to get 0.12121212... (with some approximation I guess)
The function dec2base only works for integers.
Listed in this post is a vectorized approach that works through all possible combinations of digits to select the best one for the final output as a string. Please note that because of its very nature of creating all possible combinations, it would be memory intensive and slower than a recursive approach, but I guess it could be used just for fun or educational purposes!
Here's the function implementation -
function s = dec2base_float(d,b,nde)
%DEC2BASE_FLOAT Convert floating point numbers to base B string.
% DEC2BASE_FLOAT(D,B) returns the representation of D as a string in
% base B. D must be a floating point array between 0 and 1.
%
% DEC2BASE_FLOAT(D,B,N) produces a representation with at least N decimal digits.
%
% Examples
% dec2base_float(2/5,4,4) returns '0.1212'
% dec2base_float(2/5,3,6) returns '0.101211'
%// Get "base power-ed scaled" digits
scale = b.^(-1:-1:-nde);
%// Calculate all possible combinations
P = dec2base(0:b^nde-1,b,nde)-'0';
%// Get the best possible combination ID. Index into P with it and thus get
%// based converted number with it
[~,idx] = min(abs(P*scale(:) - d));
s = ['0.',num2str(P(idx,:),'%0.f')];
return;
Sample runs -
>> dec2base_float(2/5,4,4)
ans =
0.1212
>> dec2base_float(2/5,4,6)
ans =
0.121212
>> dec2base_float(2/5,3,6)
ans =
0.101211
I have a function that converts a decimal number to binary but i need to make the function recursive. I don't know how to make this function call itself. Any help will be very appreciated.
This is my function :
function bin = myBinary (dec_nr)
i = 1;
q = floor(dec_nr/2); %this is the quotient, the "floor" function is used to round down
r = rem(dec_nr, 2); % the "rem" function is used to get the remainder which will become the first binary value
bin(i) = num2str(r(i)); % the remainder is converted and stored as a string
while 2 <= q
dec_nr = q;
i = i + 1;
q = floor(dec_nr/2);
r = rem(dec_nr, 2);
bin(i) = num2str(r);
end
bin(i + 1) = num2str(q);
bin = fliplr(bin);
save myBinary
Thank you in advance!
That's pretty simple to do. I would implement this using something called tail recursion. Remember the algorithm for converting a decimal number (assuming unsigned) into binary.
Declare a number you want to convert.
Initially declare an output to be empty.
Until the number is 0...
a. Take the number and divide this by 2
b. If there is a remainder, then attach a bit of 1 from the left, so output <- [1 output]. Else, attach a 0, so output <- [0 output].
output will contain the binary representation of your number.
With recursion, there are two cases you must consider: The base case, where the algorithm stops and gives you a known output, and a recursive case that tells you that you need to keep going, and you call the function again with modified inputs.
As such, you can very easily achieve what you want above by tail recursion by providing a helper function that takes in the input number at a given state (basically the number after being divided by 2 for a number of times) and a binary string that gives you the current state of binary string construction as you're going through and determining each bit.
You would repeatedly call this function and taking the input number and dividing it by 2 until you get a result of 0. You would start by calling the function with the original input number, and an empty string. Make sure that when you send the input number back into the function for the recursive case, you need to truncate any decimal values that result, so you would take the floor.
Therefore, a possible function is very simply:
function bin = bin2dec_recursive(in)
%// Recursive helper
function [out] = recursive_helper(in_number, binstr)
%// Base case
if in_number == 0
out = binstr; %// Just return the current binary string
%// Recursive case
else
%// Recurse - Integer divide input number and concatenate string
out = recursive_helper(floor(in_number/2), [num2str(mod(in_number,2)) binstr]);
end
end
%// call recursive helper
bin = recursive_helper(in, '');
end
What's key is this statement right here:
out = recursive_helper(floor(in_number/2), [num2str(mod(in_number,2)) binstr]);
When we hit the recursive case, we need to call the function again by dividing the input number by 2 and the input binary string is the current string, but we add either a 0 or 1 to the left of the string. We convert the number to a string by num2str.
If you desire to have a double array of single digits, simply remove the num2str call inside the recursive case, and replace '' with [] when you're calling the recursive helper function for the first time at the last line of code above.
With this, here are some examples of it working:
>> bin2dec_recursive(3)
ans =
11
>> bin2dec_recursive(5)
ans =
101
>> bin2dec_recursive(9)
ans =
1001
>> bin2dec_recursive(127)
ans =
1111111
>> bin2dec_recursive(200)
ans =
11001000
Minor Note
Be advised that the recursion limit for MATLAB is 500 calls. Therefore, with recursion, you can only compute binary numbers that are up to a maximum of 500 bits, so this means that the maximum decimal number you can put into the above function is approximately 2500 - 1. Anything more will give you an error saying that MATLAB has reached its recursion limit.
I have a strange problem with hex2dec function in Matlab.
I realized in 16bytes data, it omits 2 LSB bytes.
hex2dec('123123123123123A');
dec2hex(ans)
Warning: At least one of the input numbers is larger than the largest integer-valued floating-point
number (2^52). Results may be unpredictable.
ans =
1231231231231200
I am using this in Simulink. Therefore I cannot process 16byte data. Simulink interpret this as a 14byte + '00'.
You need to use uint64 to store that value:
A='123123123123123A';
B=bitshift(uint64(hex2dec(A(1:end-8))),32)+uint64(hex2dec(A(end-7:end)))
which returns
B =
1310867527582290490
An alternative way in MATLAB using typecast:
>> A = '123123123123123A';
>> B = typecast(uint32(hex2dec([A(9:end);A(1:8)])), 'uint64')
B =
1310867527582290490
And the reverse in the opposite direction:
>> AA = dec2hex(typecast(B,'uint32'));
>> AA = [AA(2,:) AA(1,:)]
AA =
123123123123123A
The idea is to treat the 64-integer as two 32-bit integers.
That said, Simulink does not support int64 and uint64 types as others have already noted..
I write a function to sum each row of a matrix which have three rows.
Then use a matrix which have one row and three columns to divide the previous result.
But I keep getting that error. I know the subscript should not be a decimal or negative number. But I still can not find the culprit. Please help, thanks.
% mean_access_time(ipinfo_dist, [306, 32, 192])
% 'ipinfo_dist' is a matrix which have three rows and column is not fixed.
function result = mean_access_time(hash_mat, element_num)
access_time_sum = sum(rot90(hash_mat));
result = bsxfun (#rdivide, access_time_sum, element_num);
For example:
A=
1 2
3 4
5 6
B= 7 8 9
Then I want to get
[(1+2)/7, (3+4)/8, (5+6)/9]
Update:
>> which rot90
/lou/matlab/toolbox/matlab/elmat/rot90.m
>> which sum
built-in (/lou/matlab/toolbox/matlab/datafun/#uint8/sum) % uint8 method
Culprit:
I used mean_access_time as a variable in the previous command line.
It seems like you have overridden a built-in function ( rot90 or sum ) with variable name.
Type
>> dbstop if error
And run your code.
When the error occurs type
K>> which rot90
K>> which sum
See if you get a built-in function or a variable name.