How to convert a column of float or not data into double?
6 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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?
1 Commento
Risposte (3)
Steven Lord
il 6 Giu 2025
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 Commenti
Matt J
il 6 Giu 2025
Modificato: Matt J
il 6 Giu 2025
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 Commenti
Matt J
il 8 Giu 2025
Why not simply,
B = {1, 'n/a', 3, 'n/a', 5};
B( ~cellfun(@isnumeric, B) )={nan}
Walter Roberson
il 8 Giu 2025
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
il 8 Giu 2025
Modificato: Catalytic
il 8 Giu 2025
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 Commento
Walter Roberson
il 8 Giu 2025
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])
Vedere anche
Categorie
Scopri di più su Data Type Conversion in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!