Ruut
Ruut

Reputation: 1161

setting object properties value for object array in matlab

I have created an array of objects and I would like assign a property value in a vector operation without using a for loop. Unfortunately I get an error.

A simplified example of the problem.

classdef clsMyClass < handle
   properties 
      dblMyProperty1
   end 
   methods
        function obj = clsMyClass()
        end      
   end
end 

And when running

vecMyArray = clsMyClass.empty(100,0);
vecMyArray(100) = clsMyClass;    
vecMyArray.dblMyProperty1 = 1:100;    

We get the following error:

??? Incorrect number of right hand side elements in dot name assignment. Missing [] around left hand side is a likely cause.

Any help would be appreciated.

Upvotes: 3

Views: 2006

Answers (3)

Dang Khoa
Dang Khoa

Reputation: 5823

I see what you're trying to do now. Use disperse from the MATLAB File Exchange:

>> [vecMyArray.dblMyProperty1] = disperse(1:100);
>> vecMyArray(1).dblMyProperty1
ans = 
    1
>> vecMyArray(10).dblMyProperty1
ans = 
    10

Upvotes: 1

chessbot
chessbot

Reputation: 436

You can use the deal function for exactly this purpose:

[vecMyArray.dblMyProperty1] = deal(1:100);

See: http://www.mathworks.com/company/newsletters/articles/whats-the-big-deal.html


Edit: No you can't, actually; that'll set them to all be the vector 1:100.

Upvotes: 1

macduff
macduff

Reputation: 4685

I think you'll find your answer here in "Struct array errors." Even though this is a class, similar rules apply.

Unfortunately missing [] is not the cause, since adding them causes more errors. The cause is that you cannot assign the same value to all fields of the same name at once, you must do it one at a time, as in the following code:

So you'll need:

for ii=1:100
  vecMyArray(ii).dblMyProperty1 = ii;
end

I know it's not satisfying, but I think it at least helps us to definitively understand this error.

Upvotes: 0

Related Questions