How to assign multiple variables to variables of a class that is in an array without for-loop.
1 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
Dave B
2021-10-1
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);
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!