Changing class of the variables in the table - I can't get it to work without a loop
조회 수: 16 (최근 30일)
이전 댓글 표시
See attached sample data.
It contains a table with recorded data in the following fashion:
- Column 1: duration
- Column 2: Force 1
- Column 3: Force 2
- Column 4: Speed
Every four column a new cycle is recorded.
The problem is that some of the columns are recorded as 'strings' and I want to convert them to 'double'.
I've tried a few approaches, one of them works - WAY 1 - but it involves using 'for' loop, which I want to avoid using. Ideally, I would like the WAY 2 get to work, but I don't know how. Any suggestions?
load t_sample.mat;
% Objective: convert all of the 'string' columns into 'double'
strColumnIndex = 1:2:size(t_sample,2);
copyONE = t_sample;
copyTWO = t_sample;
copyTHREE = t_sample;
copyFOUR = t_sample;
% 1st WAY:
% it works but I don't want to use the loop
for i = strColumnIndex
copyONE.(i) = cast(copyONE.(i),'double');
end
% 2nd WAY:
% It doesn't work.
tempVariable = cast(copyTWO{:,strColumnIndex},'double');
copyTWO{:,strColumnIndex} = tempVariable;
% 3rd WAY
% It doesn't work.
varNames = copyTHREE.Properties.VariableNames(strColumnIndex);
copyTHREE{:,varNames} = cast(copyTHREE{:,varNames},'double');
% 4th WAY
% Produces error
varNames1 = copyFOUR.Properties.VariableNames(strColumnIndex);
copyFOUR.varNames1 = cast(copyFOUR.varNames1,'double');
I've looked up ways of accessing data in the tables:
And to me, all 4 ways presented in the code are equivalent. What am I missing?
댓글 수: 0
채택된 답변
Peter Perkins
2018년 2월 6일
Pawel, the only way to change the type of a variable in a table is to overwrite it. Assigning with t(:,vars) = ... or t{:,vars} = ... are assignments to specific elements of the table. These syntaxes have to account for the possibility that the rows subscript might also have been, for example, 2:end-1, and you certainly would not want t(2:end-1) = ... to change the type of those variables.
Your 4th way is an error simply because you must follow the dot with a reference to only one variable. Which is to say, using dot subscripting to change the type of more than one variable is going to need a loop, as in your 1st way.
It's also possible to do something like this:
strVars = <a logical expression>
t1 = t(:,~strVars);
t2 = varfun(@(s)cast(s,'double'),t,'InputVariables',strVars];
t = [t1 t2];
but you'll also have to put things back to their original order.
Is there a specific reason why that won't work for you? Generally avoiding loops in MATLAB is a good idea, but this is not really one of those cases. If it's a readability thing, you can just make a function called something like castTextVarsToNumeric that encapsulates the loop.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Numeric Types에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!