Diluvian
Diluvian

Reputation: 25

Assign Array values to object Array in Matlab

I have the following problem:

[obj(:).Radius] = arrayOfRadius;

I have an Array with radius for every single object. The upper code doesn't work though the object has the same size as the right hand arrayOfRadius.

I could solve this with a for loop, sure:

for i = 1:length(obj)
   obj(i).Radius = arrayOfRadius(i);
end

That's not the way I'd like to solve it. I already found the "deal" function. But the deal function copies the whole arrayOfRadius() in every object.

Can someone help me out?

Thank you very much.

Upvotes: 1

Views: 388

Answers (2)

rayryeng
rayryeng

Reputation: 104504

A very hacky solution would be to take the array and turn it into a cell array, then use a comma-separated list to finally do the assignment. Assuming that obj is already declared, do something like this:

A = num2cell(arrayOfRadius);
[obj.Radius] = A{:};

num2cell converts the array into a cell array of individual elements and doing A{:} converts the cell array into a comma-separated list and we'll deal out each element into its respective slot in the structure. Doing obj.Radius unpacks each Radius field in your structure into a comma-separated list. Therefore the above code is equivalent to doing:

[obj(1).Radius, obj(2).Radius, ..., obj(N).radius] = A(1), A(2), ..., A(N)

N is the total number of elements in arrayOfRadius.

Reproducible example

>> clear
>> obj(4).Radius = 0;
>> disp([obj.Radius])
     0

>> arrayOfRadius = [1 2 3 4];
>> A = num2cell(arrayOfRadius);
>> [obj.Radius] = A{:};
>> disp([obj.Radius])
     1     2     3     4

My Two Cents...

FWIW, using the for loop approach is actually more readable. Doing this workaround really makes the code obfuscated... especially if you're only copying elements from an array to a structure. How many times is this copying going to be performed? If it's only once or a few times, stick with the for loop for readability.

Upvotes: 4

sco1
sco1

Reputation: 12214

This is one of the more obnoxious areas of MATLAB's indexing that I really wish they would fix, especially with the move of graphics handles to objects from doubles making it non-intuitive how to set properties of multiple objects at the same time.

There exists a workaround for deal, though it requires the intermediate use of num2cell:

% Initialize a structure
obj(6).radius = 6;

radii = [1 2 3 4 5 6];
C = num2cell(radii);
[obj(:).radius] = deal(C{:});

Which returns:

>> [obj.radius]

ans =

     1     2     3     4     5     6

As desired.

Upvotes: 5

Related Questions