1

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

OmG
  • 18,337
  • 10
  • 57
  • 90
Dryland
  • 86
  • 1
  • 3

1 Answers1

0

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,

jespestana
  • 565
  • 5
  • 13
  • Thanks, but this is not what I want. Because my '@Multiply' do many other things with different fields in the struct (not only multiply number like in your code). So 1) I can't use '@prod' 2) I have to pass in the whole struct as 2nd argument, and that doesn't seem to work. – Dryland Oct 15 '12 at 04:33
  • I have faced many times similar problems to yours. With cell arrays and structure arrays I think that you do not have any other option a part from using a for loop... The vertcat() trick is useful to concatenate the values on only one field of the struct array. Let's see if somebody has good answer for you question; I am curious to see if it works also with cell arrays... – jespestana Oct 15 '12 at 13:15