How to convert cell to double for creating variables from table?
Show older comments
I have a csv file which contains three types of information. The top row is a the header. The second row is the units for the parameters in the header. The third row and following is data for that parameter (see attached example file). I am trying to create variable in the workspace with the same names as the header. These variables need to be assigned to the data. Using a piece of sample of code which I found on MATLAB Answers, it does everything I need it to do, except the data type for the variables results in "cell" instead of "double". I need double to be able to do computations with the variables. Also, I am looking for a solution which does not utilize DelimitedTextImportOptions. My workstation at my employer only has MATLAB 2013b. . . and there is no hope they will upgrade. Thank you in advance for your help! Here is the code so far:
clc, clear
data = readtable('TestFindVar.csv');
numdata = data(2:end,:)
for i=1:width(numdata)
x = numdata.Properties.VariableNames(i);
eval(sprintf('%s = numdata.%s', x{1}, x{1}));
end
Accepted Answer
More Answers (1)
Peter Perkins
on 11 Dec 2016
0 votes
Steve, the root cause of your problem is that second line in the file: readtable is seeing text in the first line of data, and creating all text variables. If you're using the most recent version of MATLAB, R2016b, you should look at the detectImportOptions function to control how readtable interprets that line. If not, you can at least skip that line using the HeaderRows parameter to readtable, and read it in later if need be.
This is more than a convenience, if your file is large, text will take up much more memory than numeric.
Hope this helps.
2 Comments
Walter Roberson
on 12 Dec 2016
User's employer is stuck at R2013b unfortunately.
Peter Perkins
on 12 Dec 2016
Ah, right you are, I didn't catch that.
Still, the HeaderRows parameter has been around since R2013b, and using that would avoid reading in the numbers as strings.
Categories
Find more on Cell Arrays 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!