How to make Accumarray work with Struct array?

293 views Asked by At

Can this be done? Basically, I have a struct array val (contains a list of my custom structure) and I want to multiply all the elements together using custom multiply function Multiply and I don't want to use loop.

I tried to use accumarray(indx, val', [1 1], @Multiply) with indx=ones(lengths(val), 2) but this doesn't work (at least for Octave 3.4.3). When execute, inside my C=Multiply(A,B) function, A is passed the whole struct array, and B is empty instead of A is the first element of the array and B is the second element as in normal case.

Hope I made myself clear here. Thanks

1

There are 1 answers

2
jespestana On

I am not sure what you wanted to do. I have worked out some code related to what you expected:

val = 101:105;
strct_template.index = 1;
strct_template.b = 1;
strct_array = repmat(strct_template,length(val),1);

for i=1:length(val)
    strct_array(i).index = i;
    strct_array(i).b = val(i);
end

subs = [1; 2; 4; 2; 4];
sum_example = accumarray(subs, vertcat(strct_array.b)) % example from accumarray in matlab help 
mult_example = accumarray(subs, vertcat(strct_array.b),[],@prod)
subs = ones(length(strct_array),1);
mult_example2 = accumarray(subs, vertcat(strct_array.b),[],@prod) % I suppose you wanted this
mult_example3 = prod(vertcat(strct_array.b)) % which gives the same result as this

It is the first time I use the accumarray function, so maybe I am misunderstanding what you needed. Hope I could help,