MATLAB: Does matlab convert all fields of structure to double

data formatstructures

I created a function that analyzes data and stores analysis in a structure. To save space, I convert some of the data to logical, however when I save the structure to a file, this field is converted back to a double. I even ask if the variable is logical directly after placing data in field as a variable and it is a double. If I save it outside of the function, this works fine. What am I doing wrong?
peak_data.raster(:,:,1) = logical(data_dark);
peak_data.raster(:,:,2) = logical(data_light);
if ~islogical(peak_data.raster)
error('Data format is incorrect')
end

Best Answer

When you assign data of one type into a portion of an array of a different type, the data of the first type is converted to the type of the array into which you're assigning.
For example:
x = single([1 2 3 4 5]);
y = 6;
whos % note x is single and y is double
x(4) = y;
whos
The assignment statement doesn't change the type of either x or y. The fourth element of x after the assignment is single(y) which is single(6).
Contrast this with:
w = single([1 2 3 4 5]);
z = 6;
whos % w is a 1x5 single vector and z is a 1x1 double
w = z;
whos % now w and z are both 1x1 double
This is because you're not assigning z to a portion of w, you're overwriting w entirely with z.
So if peak_data.raster was a double array before you assigned the logical array logical(data_dark) into a portion of it, the logical array is converted to double then stored in the portion of peak_data.raster.