Indexing custom array class objects
4 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
per isakson
on 2 Feb 2015
Try this
newModulus = {35,20};
[mat([1,3]).Modulus] = deal( newModulus{:} ); % this does work
More Answers (0)
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!