Vectorized Sum Over Indexes

27 views
Skip to first unread message

Omid

unread,
Jun 17, 2014, 9:29:37 AM6/17/14
to yal...@googlegroups.com
Dear Johan,

I would like to sum over indexes using "accumarray" function in MATLAB in order to avoid using for loops. However, this function does not accept 'sdpvar' as input argument. Is there any way to escape for loops ?

Thank you in advance.

Best,
Omid

PS. Example

For instances the following code without sdpvar is fine
Set = [1 1 1 2 6 6 ];
Val = [0.5 0.2 0.5 0.3 0.6 0.7];
Output = accumarray(Set',Val',[10 1]);

But the following with sdpvar gives error:
Set = [1 1 1 2 6 6 ];
Val = sdpvar(6,1);
Output = accumarray(Set',Val',[10 1]);

Johan Löfberg

unread,
Jun 17, 2014, 9:55:29 AM6/17/14
to yal...@googlegroups.com
You would have to write a function which does the same thing. If you want, you can overload it

Place the following in a file @sdpvar/accumarray.m
function A=accumarray(subs,val)
%ACCUMARRAY (overloaded)

A
= [];
for i = 1:max(subs)
    j
= find(i == subs);
   
if isempty(j)
        A
= [A;0];
   
else
       
% subsref from method fails sometimes due to some weird overloading
       
% rules in MATLAB, so we jump outside method and do the subsref
       
% there instead
       
%A = [A;sum(A(j))];
        A
= [A;sum(extsubsref(val,j))];
   
end
end

and the simple case is handled at-least
>> x = sdpvar(1,5);A = accumarray(subs,x);sdisplay(A)

ans
=

   
'x(1)'
   
'x(2)+x(4)'
   
'0'
   
'x(3)+x(5)'

In other words, the for-loops can not be avoided ,it is just a matter of where they are (well, of course the whole thing can be vectorized if performance is wanted since the whole operation can be seen as a matrix-vector multiplication)
Reply all
Reply to author
Forward
0 new messages