something akin to singleton expansion in object array assignment

조회 수: 1 (최근 30일)
Val Schmidt
Val Schmidt 2013년 12월 9일
댓글: Alfonso Nieto-Castanon 2013년 12월 10일
Hello, I'm writing to inquire if anyone knows if it's possible to create an object array and to assign a single field many values all at once - sort of like A(1:5) = ones(1,5);. For example.
classdef bug
properties
legs
end
end
for i=1:5
bugs(i) = bug();
end
% This doesn't work.
bugs(1:5).legs = [6 6 8 8 4];
% This doesn't either
bugs.legs = [6 6 8 8 4];
% Or this
bugs.legs = 6
Does one have to write a loop or maybe modify subsasgn (ugh). It seems like all other functionality available to other matlab objects is available with the built in subsasgn but this one.
Thanks in advance,
Val

답변 (2개)

Walter Roberson
Walter Roberson 2013년 12월 9일
Singleton expansion does not use that syntax for regular objects. Experiment with
L = num2cell([6 6 8 8 4]);
bugs(1:5).legs = L{:};
  댓글 수: 2
Val Schmidt
Val Schmidt 2013년 12월 9일
Thanks for the suggestion. I gave it a go and several variations on the theme. Embarrassingly, I'm missing the one that works:
a.legs = {ones(1,5)}
Incorrect number of right hand side elements in dot name assignment. Missing [] around left hand side is a likely cause.
a(:).legs = {ones(1,5)}
Insufficient number of outputs from function on right hand side of equal sign to satisfy overloaded assignment.
b = num2cell(ones(1,5));
a(1:5).legs = b{:};
Insufficient number of outputs from function on right hand side of equal sign to satisfy overloaded assignment.
a(1:5).legs = b(:);
Insufficient number of outputs from function on right hand side of equal sign to satisfy overloaded assignment.
What did I miss do you think?
-Val
Walter Roberson
Walter Roberson 2013년 12월 9일
You could try
b = num2cell(ones(1,5));
a(1:5).legs = deal(b{:});
or
[a(1:5).legs] = deal(b{:});
deal() should not be necessary anymore, but it was around R2007a-ish that that changed.

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


per isakson
per isakson 2013년 12월 9일
편집: per isakson 2013년 12월 9일
Or hide the num2cell in a function
>> [bugs.legs] = num2list( [12 13 14 8 4] )
bugs =
1x5 bug array with properties:
legs
where
function varargout = num2list( num_vec )
% num2list
varargout = num2cell( num_vec );
end
  댓글 수: 3
per isakson
per isakson 2013년 12월 10일
편집: per isakson 2013년 12월 10일
I just tried to illustrate an idea. The code works here when the length of the object array and the vector are the same. Matlab mostly requires that the length (/size) of LHS and RHS are equal(?).
Yes, one may allow the LHS to be shorter and it is possible to implement singleton expansion.
Alfonso Nieto-Castanon
Alfonso Nieto-Castanon 2013년 12월 10일
Or even: (also without the checks)
% num2list
function varargout = num2list(varargout)
end

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

카테고리

Help CenterFile Exchange에서 Graphics Object Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by