Isolate first non-zero integer of each element of an array
Afficher commentaires plus anciens
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)
Réponse acceptée
Plus de réponses (1)
Ameer Hamza
le 22 Sep 2020
Modifié(e) : Ameer Hamza
le 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
1 commentaire
Adam Nasinski
le 22 Sep 2020
Catégories
En savoir plus sur Logical dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!