How to convert cell to double for creating variables from table?

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

VN = data.Properties.VariableNames;
for K = 1 : length(VN)
FileData.(VN{K}) = str2double(data.(VN{K})(2:end));
end
You can adjust the name of the structure FileData at need.
Afterwards, you would have FileData.ClntFlow and FileData.EngOilTemp . You would not have ClntFlow and EngOilTemp as direct variables in your workspace; see http://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval

More Answers (1)

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

User's employer is stuck at R2013b unfortunately.
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.

Sign in to comment.

Categories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!