In what situations do we need to use the `empty` method? What benefits does the `empty` method provide?
4 次查看(过去 30 天)
显示 更早的评论
method empty creat an empty array.In 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 this in command line.
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
A = ColorInRGB.empty(0,5);
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
B=ColorInRGB1()
0 个评论
回答(1 个)
Stephen23
2023-8-26
移动:Matt J
2023-8-26
"In what situations do we need to use the `empty` method?"
Whenever you want to create an empty array of a certain class. Certainly the syntactic shortcuts [] and '' get used a lot to create empty double/char arrays respectively and I see no reason why it should not be required by users to also create empty arrays of other classes, so the simple answer to your question is "whenever the programmer might want to create an empty array of a particular class".
"What's the difference between A and B?"
A is empty.
B is not empty.
"What's the distinction between an empty 1x0 and an empty 1x1?"
1x0 is empty.
1x1 is not empty.
"Or is there any distinction between a 5x0 and a 1x1 empty?"
5x0 is empty.
1x1 is not empty.
The distinction is very simple: the size is different. Although scalars are a special case, in general it is not possible to e.g. concatenate arrays with incompatible sizes along the dimension being concatenated. So a very basic usecase is to preallocate an empty array of the correct dimensions and class before a loop, which gets concatenated onto during the loop.
It seems like you need to revise some basic MATLAB concepts, e.g. what an empty array is:
It might help to practice some more basic MATLAB before jumping into OOP.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!