Indexing custom array class objects

조회 수: 4 (최근 30일)
Nick
Nick 2015년 2월 2일
댓글: Nick 2015년 2월 3일
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?

채택된 답변

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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by