How to convert a cell array of singles and doubles to an array of a single type (double)?

13 ビュー (過去 30 日間)
I queried a database for an array of numerical values. The query is a function call that returns a struct of different cell-arrays (one of which is "struct.speed"). I tried use cell2mat() to convert each cell element to an array (of a uniform type, which is what cell2mat does) but I found out that some cells contained `singles` while others contained `doubles` (doubles where there were NaN values).
Attached is "struct.speed" (as well as the original struct) and the call I used to check the type of each cell element was:
cellfun(@class, struct.speed(:,1), 'UniformOutput', false);
I tried calling typecast and it produced an error I didn't understand:
EDITED: Oh right -- struct.speed(:,1) is a cell array and type cast only works on numeric values (or arrays of them).
K>> typecast(struct.speed(:,1), 'double')
??? Error using ==> typecastc
The first input argument must be a full, non-complex numeric value.
Error in ==> typecast at 31
out = typecastc(in, lower(datatype));
I need to do the type casting because I wanted to use slice-notation to assign the result to another struct "WHBB.Speed":
WHBB.Speed(:, bin) = struct.speed(:,1); % Error: Conversion to double from cell is not possible
The above statement works for slices of struct.speed that doesn't contain a mix of NaN's and numeric values (slices of all NaNs or slices of all doubles)
  2 件のコメント
Stephen23
Stephen23 2018 年 9 月 19 日
Do NOT call your variable struct, as this shadows the inbuilt struct function.
Minh Tran
Minh Tran 2018 年 9 月 25 日
Thank you for pointing that out.

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

採用された回答

Stephen23
Stephen23 2018 年 9 月 19 日
編集済み: Stephen23 2018 年 9 月 19 日
Assuming that each cell contains a scalar value:
cellfun(@double,myStruct.speed)

その他の回答 (1 件)

Minh Tran
Minh Tran 2018 年 9 月 19 日
編集済み: Minh Tran 2018 年 9 月 19 日
A solution I just came up with that is kind of clunky:
result = NaN(size( struct.speed(:,1) )); % Preallocate a vector of NaNs
for i=1:length(struct.speed(:,1))
result(i) = double( struct.speed{i,1} ); % Element wise conversion of all elements to doubles
end

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by