Assigning blank cell array confuses Matlab with data type

1 次查看(过去 30 天)
Hi,
I have two cases as below. I want to have both x_cell and x to be single but the first case doesn't give me so. This is the simplified code to represent a bigger problem so it is written in that way because the original code uses parfor so need the blank assigning, and I need to save memory so too many data conversions are not desired. Is there any way to deal with this?
clc;
%% Case 1: assign cell array to be blank
clear all;
x_cell{1} = [];%assigning
for n = 1:10
x_cell{1}(n) = single(1);%data type we want is single
end
x = x_cell{1};%don't want to make it x=single(x_cell{1}) because the purpose is
% to make both x_cell and x single to save memory
whos x %this result into double, undesired
%% Case 2: without assigning cell array
clear all;
for n = 1:10
x_cell{1}(n) = single(1);
end
x = x_cell{1};
whos x %this result into single which is desired
Thanks

采纳的回答

Stephen23
Stephen23 2018-12-16
编辑:Stephen23 2018-12-16
x_cell = {single([])}; % assign.
Note that your code expands the numeric array on each iteration, which is inefficient. It is recommended to preallocate the complete numeric array before the loop, e.g.:
x_cell = {nan(1,10,'single')}; % preallocate.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by