How to convert a column of float or not data into double?
4 次查看(过去 30 天)
显示 更早的评论
My data column can be float numbers throughout, e.g.
A = [1, 2, 3];
or a strings, like the below
B = [1, 2, 3, 'n/a', 5];
Is there a universal function that can convert both into numerical values? Or do I have to use a loop to check if they are float or not?
回答(3 个)
Steven Lord
2025-6-6
Are you trying to import this data from a file? If so please show us (or tell us, if you can't provide the code) exactly how the data looks in the file and which tools / functions you're using to import it. Depending on the specific tool there may be an option to control what gets imported as missing data.
If you want to type this and have MATLAB automagically know that it ought to replace the 'n/a' with NaN, there is no such function. Instead what will happen is that MATLAB will convert the three characters in 'n/a' into their numerical values and store those numerical values in the numeric vector.
B = [1, 2, 3, 'n/a', 5]
If you entered this data as strings instead:
B = [1, 2, 3, "n/a", 5]
you could replace the "n/a" with "NaN" or the missing string and then call double on the resulting string array.
C1 = replace(B, "n/a", string(missing))
C2 = double(C1)
C3 = replace(B, "n/a", "NaN")
C4 = double(C3)
C5 = standardizeMissing(B, "n/a") % treat "n/a" as missing
C6 = double(C5)
0 个评论
Matt J
2025-6-6
编辑:Matt J
2025-6-6
It is not possible for an array to hold both numeric floats and chars unless it is a cell array. That being the case, it is easy to convert to double (EDIT: assuming the numbers are integers like in your example, or have less than 5 decimal points precision):
B = {1, 2, 3, 'n/a', 5};
out = str2double(string(B))
5 个评论
Matt J
2025-6-8
Why not simply,
B = {1, 'n/a', 3, 'n/a', 5};
B( ~cellfun(@isnumeric, B) )={nan}
Walter Roberson
2025-6-8
It depends on whether the strings might represent valid numeric data.
B = {1, '2.34', 3, 'n/a', 5};
mask = cellfun(@isnumeric, B);
B(~mask) = cellfun(@str2double,B(~mask),'uniform',0)
B = {1, '2.34', 3, 'n/a', 5};
B( ~cellfun(@isnumeric, B) )={nan}
Catalytic
2025-6-8
编辑:Catalytic
2025-6-8
format long
source = {'0.12345678987654321', pi,'n/a'};
target = [0.12345678987654321, pi,nan];
output = cellfun( @(c) str2double(num2str(c,17)), source)
isequaln(output,target)
1 个评论
Walter Roberson
2025-6-8
Interesting, I just happened to notice
fprintf('%.999g\n', pi)
fprintf('%.999g\n', pi*1e30)
The representation of pi here goes ... 8979311 but the representation of pi*1e30 goes ... 8979321 so the multiplication by 1e30 leads to different rounding. (Incidentally, true pi goes ... 8979323[8])
另请参阅
类别
在 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!