Passing string as function variable for renaming table column

2 views (last 30 days)
I am trying to pass a string variable to a custom function to rename a table column title.
My code is below:
temperature = 'OPC.Temperature.BottomTemperature';
temp_column_name = 'Temperature';
%extract bottom temperature data
data_temp = dataextract(data_temp,temperature,temp_column_name);
Below is the function:
function [ data ] = dataextract( data_array,variable,column_name )
%remove all rows not containing variable in column 2
data_string = variable;
data_comp = strcmp(data_array(:,2),data_string);
data_comp = ~data_comp;
data_array(data_comp,:) = [];
%remove extra information from columns 3 & 4 from data array
data_array(:,(2:4)) = [];
%convert data_array cell array to table
data_array = array2table(data_array,'VariableNames',{'TimeStamp', column_name});
%convert timestamp string to datetime
data_array.TimeStamp = datetime(data_array.TimeStamp,'InputFormat','yyyy-MM-dd HH:mm:ss.SSS');
%convert beam current string to double precision value
data_array.column_name = str2double(data_array.column_name);
data = data_array;
end
I tried to initially just pass 'Temperature' in the function but that would not work and now a variable won't pass either. Below is my error:
Error using dataextract (line 18)
Unrecognized variable name 'column_name'.
Error in parser_test (line 38)
data_temp = dataextract(data_temp,temperature,temp_column_name);

Accepted Answer

Walter Roberson
Walter Roberson on 13 Dec 2017
Change
data_array.column_name = str2double(data_array.column_name);
to
data_array.column_name = str2double(data_array.(column_name));
  1 Comment
jcledfo2
jcledfo2 on 14 Dec 2017
Thanks!!
I had to also add () to the beginning or it added an extra column
data_array.(column_name) = str2double(data_array.(column_name));

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!