Hello,
I am trying to change all variables in a table from int64 to double. I know I should use the "double" function, but for some reason it is not working. Please keep in mind I will be changing multiple columns from int to double. Here is an example:
tbl1 = table(int64(randi([1,100],[10,1])),randn([10,1]),'VariableNames',["x1","x2"]);
tbl1.x1 % verify that x1 is in fact int64
ans =
10×1 int64 column vector
44
39
77
80
19
49
45
65
71
76
intCols = varfun(@isinteger,tbl1,'OutputFormat','uniform'); % get all integer columns in the table, in my case there are several
tbl1(:,intCols) = varfun(@double,tbl1(:,intCols)); % apply double to all columns and reassign them to the table
tbl1.x1 % in my case, they are still of the type int64
ans =
10×1 int64 column vector
44
39
77
80
19
49
45
65
71
76
What am I doing wrong? thank you

 採用された回答

Walter Roberson
Walter Roberson 2022 年 3 月 30 日

0 投票

You need to replace the entire varible using dot syntax. For example,
tbl1.x1 = double(table1.x1);
to do that for several variables, you would pretty much need to loop using dynamic field names.
Alternatives:
If you do not mind potentially reordering the fields, then you could
notIntCols = setdiff(1:width(tabl1), IntCols);
tabl1 = [tabl1(:,notIntCols), array2table(double(tabl1(:,IntCols)), 'VariableNames', tabl1.Properties.VariableNames(IntCols))]
and you could probably do the same thing using addvars() https://www.mathworks.com/help/matlab/ref/table.addvars.html
Another approach would be to use table2cell(), replace the IntCols columns in the cell with double() of those columns, then cell2table()

4 件のコメント

dleal
dleal 2022 年 3 月 30 日
thank you! Exactly what I needed
dleal
dleal 2022 年 3 月 31 日
Hi Walter Roberson, the three solutions you mention above work, but could you please briefly explain what in MATLAB does not allow my suggested method to work?
tbl1(:,intCols) = varfun(@double,tbl1(:,intCols))
(I know in R and Python these are valid assignments).
Steven Lord
Steven Lord 2022 年 3 月 31 日
When you use indexed assignment, MATLAB tries to convert the quantity being assigned (on the right) into the type of the quantity being assigned into (on the left.)
x = int8(1:5)
x = 1×5
1 2 3 4 5
x(1) = pi
x = 1×5
3 2 3 4 5
In that code, pi returns a double so when it is assigned into x using indexed assignment MATLAB converts that double into the int8 value 3 then performs the assignment. So your varfun worked, but then MATLAB immediately converted the double results back to the original type of those variables, int64.
dleal
dleal 2022 年 3 月 31 日
I understand Steven, thanks for your answer, it is all clear now

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

製品

リリース

R2022a

質問済み:

2022 年 3 月 30 日

コメント済み:

2022 年 3 月 31 日

Community Treasure Hunt

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

Start Hunting!

Translated by