In what situations do we need to use the `empty` method? What benefits does the `empty` method provide?

7 Ansichten (letzte 30 Tage)
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()

Antworten (1)

Stephen23
Stephen23 am 26 Aug. 2023
Verschoben: Matt J am 26 Aug. 2023
"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.

Kategorien

Mehr zu Construct and Work with Object Arrays finden Sie in Help Center und File Exchange

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by