Clear Filters
Clear Filters

Assigning blank cell array confuses Matlab with data type

2 views (last 30 days)
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

Accepted Answer

Stephen23
Stephen23 on 16 Dec 2018
Edited: Stephen23 on 16 Dec 2018
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.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!