Object array implemenation in MATLAB OOP

1 vue (au cours des 30 derniers jours)
Jack
Jack le 2 Jan 2015
Commenté : Jack le 5 Jan 2015
Suppose that we have this class in MATLAB R2014b :
classdef Pre
properties
Value
end
methods
function obj = Pre(F)
if nargin ~= 0
m = size(F,1);
n = size(F,2);
obj(m,n) = Pre;
for i = 1:m
for j = 1:n
obj(i,j).Value = F(i,j);
end
end
end
end
end
end
1) If we erase if nargin~=0 from this code we have this error :
Error using Pre (line 13)
Not enough input arguments.
Error in Pre (line 15)
obj(m,n) = Pre;
Why? I think this is only checking for number of input arguments !
2) what is obj(m,n) = Pre;? what this line is doing in this code? This is for pre-allocating but how this line can do that?
I checked this class with this syntax: az = Pre([2 3 5;5 3 0])

Réponse acceptée

Geoff Hayes
Geoff Hayes le 2 Jan 2015
Jack - the error message, Not enough input arguments, makes sense since the code is calling the class constructor at the line
obj(m,n) = Pre;
without any input arguments. So when the line
m = size(F,1);
is executed, there is no F and the error appears. Try putting a breakpoint at this line, and then create an instance of this class to verify when this error is being generated.
As for what the line
obj(m,n) = Pre;
is doing, it is just creating an mxn array of objects of the type Pre. This is typical MATLAB code where you want to initialize an array (or matrix) with an object of a data type. For example,
array1(3,5) = uint8(0)
creates a 3x5 array of 8-bit unsigned integers, whereas
array2(12,3) = single(0)
creates a 12x3 array of elements of the single data type.
  1 commentaire
Jack
Jack le 5 Jan 2015
Thank you for answer Geoff.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Construct and Work with Object Arrays dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by