How to assign multiple variables to variables of a class that is in an array without for-loop.

1 view (last 30 days)
I found it difficult to formulate my question. Here is my problem:
classdef myClassA <handle
properties
arrayOfMyClassB
end
end
classdef myClassB <handle
properties
age;
end
end
function example()
%say arrayOfClassB have 10 elements and i want to sign element 5 to
%10 age 7. What I though I could do was as follows:
instanceOfMyClassA.arrayOfMyClassB(5:10).age = 10;
%I get error:
%Expected one output from a curly brace or dot indexing expression, but there were 2
%results.
end
I understand what goes wrong and that I can fix it with a for-loop. My problem is that in a code I have written I do this alot. Therefore I am wondering if there is a simple way to fix this without needing to write for-loops?

Accepted Answer

Dave B
Dave B on 1 Oct 2021
I'm not sure I recommend it, as it's non trivial to read, but I'm pretty sure in this particular case you can do:
[instanceOfMyClassA.arrayOfMyClassB(5:10).age] = deal(10);
This was my test code (with your class definitions):
instanceOfMyClassA = myClassA;
instanceOfMyClassA.arrayOfMyClassB = myClassB;
instanceOfMyClassA.arrayOfMyClassB(2) = myClassB;
instanceOfMyClassA.arrayOfMyClassB(3) = myClassB;
instanceOfMyClassA.arrayOfMyClassB(4) = myClassB;
[instanceOfMyClassA.arrayOfMyClassB(1:2).age] = deal(10);
[instanceOfMyClassA.arrayOfMyClassB(3:4).age] = deal(1);
An alternative, if you're willing to go down a little rabbit hole, is to override subsasgn...

More Answers (0)

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!