Isolate first non-zero integer of each element of an array
1 view (last 30 days)
Show older comments
Adam Nasinski
on 22 Sep 2020
Commented: Adam Nasinski
on 22 Sep 2020
Lets say,
A is some 2D array such that A = [m n] with both large values (e10) and tiny decimal values (e-15)
For Example,
A = [0.00663270674527115 36798861787.4757 0.0165559157141383
0.00845305563147772 0.000298646998074807 2561194549424.91]
I need an array such that,
B = [6 3 1
8 2 2]
Methods I've tried
Large multiplier
- B = A * 10^10; %multiply by large number to remove leading zeros
- B = fix(B./10.^fix(log10(B))); %isolate first value of each element
- I got a higher than expected amount of 1's with this method - perhaps matlab has a value limit
Format as Scientific first
- B = sprintf('%0.5g',A); %convert each element to scientific notation (no leading zeros)
- B = fix(B./10.^fix(log10(B))); %isolate first value of each element
- This creates a string - not an array. Its slow and not a great solution
- I've also tried format short eng, but to my understanding that doesn't seem to effect the array itself just the displayed answer
- fprint seemed promising but got an error calling in array A
B = fprintf(A,'%1.5s',0.1)
0 Comments
Accepted Answer
Bruno Luong
on 22 Sep 2020
Edited: Bruno Luong
on 22 Sep 2020
A = [0.00663270674527115 36798861787.4757 0.0165559157141383
0.00845305563147772 0.000298646998074807 2561194549424.91]
Then
AA = abs(A); % in case A negative
B = floor(AA./(10.^floor(log10(AA))))
returns
B =
6 3 1
8 2 2
B contains NaN at the place where A is 0 (normal not avoid this special case).
More Answers (1)
Ameer Hamza
on 22 Sep 2020
Edited: Ameer Hamza
on 22 Sep 2020
Are values stored in a .txt file? Because MATLAB floating-point types cannot contain values with such precision. The following assumes that the values are present in a .txt file
str = fileread('data.txt');
str = strrep(str, '0', '');
str = strrep(str, '.', '');
out = regexp(str, '(\d)\d*', 'tokens');
out = [out{:}];
out = cellfun(@str2double, out);
out = reshape(out, 3, []).';
data.txt is attached.
Result
>> out
out =
6 3 1
8 2 2
See Also
Categories
Find more on Data Type Conversion 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!