Isolate first non-zero integer of each element of an array
1 回表示 (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
Bruno Luong
2020 年 9 月 22 日
編集済み: Bruno Luong
2020 年 9 月 22 日
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).
その他の回答 (1 件)
Ameer Hamza
2020 年 9 月 22 日
編集済み: Ameer Hamza
2020 年 9 月 22 日
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
参考
カテゴリ
Help Center および File Exchange で Data Type Conversion についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!