Assigning blank cell array confuses Matlab with data type

1 Ansicht (letzte 30 Tage)
Dave Lee
Dave Lee am 16 Dez. 2018
Bearbeitet: Stephen23 am 16 Dez. 2018
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

Akzeptierte Antwort

Stephen23
Stephen23 am 16 Dez. 2018
Bearbeitet: Stephen23 am 16 Dez. 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.

Weitere Antworten (0)

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Produkte


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by