The method empty creates an empty array. What situations do we need to use the empty method? What benefits does the empty method provide? Will it lead to efficiency improvements through preallocation? Do they have different implications for the user?
Input:
A = ColorInRGB.empty(1,0);
B = ColorInRGB1();
A is 1x0 ColorInRGB, memorysize=0.
B is 1x1 ColorInRGB, memorysize=0.

What's the difference between A and B? What's the distinction between an empty 1x0 and an empty 1x1? Or is there any distinction between a 5x0 and a 1x1 empty? If there's no difference, why do we use the empty method?
ColorInRGB.m
classdef ColorInRGB
properties
Color (1,3) = [1,0,0];
end
methods
function obj = ColorInRGB(c)
if nargin > 0
obj.Color = c;
end
end
end
end
ColorInRGB1.m
classdef ColorInRGB1
properties
Color; % (1,3) = [1,0,0];
end
methods
% function obj = ColorInRGB(c)
% if nargin > 0
% obj.Color = c;
% end
% end
end
end
2023/08/27 12:59 These two classes are different. My question is, ColorInRGB1() can help me obtain an empty array, so why do we still need an 'empty method'? Once I know the differences between them, I can understand when to use ColorInRGB1() in what scenarios and when to use ColorInRGB.empty(1,0); in others.
Bis a 1x1 object array whose only field is an empty array.Ais a 1x0 object, it has no elements.Bis not an empty array, but it contains an empty array.Ais an empty array.I understand why the distinction is not directly obvious. Both contain no data (this is the “memory size” reported by the workspace explorer and the
whoscommand, which doesn’t include the overhead of the object itself). But there are clear differences:isemptytest is true forAbut not forB.B:B(1)is valid,A(1)is not.B.Coloris valid, as is the assignmentB.Color = 'foo'; you can do neither withA.This is exactly the same as the difference between the empty cell array
{}and the 1x1 cell array{[]}, which contains an empty array.If you are curious about why
emptycan create a 1x0 array, as opposed to only a 0x0 array, and why we want empty arrays at all, see this question and this other one.