Indexing custom array class objects

4 visualizaciones (últimos 30 días)
Nick
Nick el 2 de Feb. de 2015
Comentada: Nick el 3 de Feb. de 2015
To ask the questions I am going to give a simple example of what I would like to do. I have a custom Material class given here.
classdef Material < handle
properties
Modulus;
Name;
end
methods
% constructor
function mat = Material(name,modulus)
if nargin > 0
mat.Name = name;
mat.Modulus = modulus;
end
end % function mat = Material(name,modulus)
function set.Modulus(mat,newModulus)
mat.Modulus = newModulus;
end % function set.Modulus(mat,newModulus)
function set.Name(mat,newName)
mat.Name = newName;
end % function set.Name(mat,newName)
function modulus = get.Modulus(mat)
modulus = mat.Modulus;
end % function modulus = get.Modulus(mat)
function name = get.Name(mat)
name = mat.Name;
end % function name = get.Name(mat)
end % methods
end % classdef Material
Here is some working code using the class:
mat1 = Material('A',30); % material A
mat2 = Material('B',25); % material B
mat3 = Material('C',45); % material C
mat = [mat1; mat2; mat3];
% get modulus values of A & C
mods = [mat([1,3]).Modulus]'; % this works nicely to get a vector of the modulus values
I would now like to update all the modulus values at once using a vector of them. Following MATLAB's general indexing the command would be:
% new modulus values
newModulus = [35; 20];
% update modulus values of A & C
mat([1,3]).Modulus = newModulus; % this does not work
However, this gives an error message. I believe MATLAB is purposely designed to not do the above statement, I think I read that in documentation someplace but have not been able to find it back. My question is, is there a way to implement such a thing myself, without using a for loop?
As of now the only way I can see implementing it is by using a for loop to loop over each value in the vector newModulus. Is using a for loop the only way? Or the best way? Or is there some way using MATLAB's built in matrix/vector notation or a built in function?
Is there a way to do this by overloading the subsasgn method in my class? Or do I need to create another class that has an array of Material objects and that class overloads the subsasgn method?

Respuesta aceptada

per isakson
per isakson el 2 de Feb. de 2015
Try this
newModulus = {35,20};
[mat([1,3]).Modulus] = deal( newModulus{:} ); % this does work
  1 comentario
Nick
Nick el 3 de Feb. de 2015
Yes, that works. I was not aware of the deal function. That is exactly what I needed. Thank you!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Data Type Identification en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by