How can I take the values of one array, map the values as indices to another array, then generate a thrid array with the sum of former's elements??

I know the question is a bit confusing, so let me illustrate what i am trying to do with an example:
A = [ 2 1 4 2 3 2 4 0 ]
B = [ 1 1.5 2 1.5 2.5 3 1 ]
Now what I need is C = [ 1.5 5.5 2.5 3 ] Here is an explanation:
A[2] = 1 , so B[2] = C[1]
A[1], A[4], A[6] = 2, so B[1]+B[4]+B[6]= C[2]
A[5] = 3 so B[5] = C[3]
A[3], A[7] = 4 so B[3]+B[5] = C[4]
The index elements from A with common values (or a particular value) are mapped to B(same indices), then the elements with those indices in B are added (if one value, directly become elements in C) to get array C such that the values of A are indices of C.
Edited: A[8] = 0, so neglect that value.

 Akzeptierte Antwort

You can use ACCUMARRAY. ACCUMARRAY is designed to take column vectors, not row vectors. So use this:
accumarray(A(:),B(:),[max(A) 1])'
Hope this helps!
-Greg

10 Kommentare

I tried it and got this -
Error using accumarray First input SUBS must contain positive integer subscripts.
Error in Sysmodel (line 69) APload=accumarray(index(:), Userload(:), [max(index) 1])';
Is it because index is a 1x93 double?
Probably because you have values in index(:) less than or equal to zero.
Yes, index does have values equal to 0, what can be done to resolve this error?
What do you want the value of C to be if the value in A is 0? There is no zeroeth column of B. Do you just want to add 1 to index (A) before you start?
If the value in A is 0, then i don't want to consider it, i.e. i want that value to be neglected.
Then do this:
t = A>0;
C = accumarray(A(t),B(t),[max(A) 1])';
or even this:
t = (A>0)&(A==round(A));
C = accumarray(A(t),B(t),[max(A) 1])';
if A has negative or fractional values.
Then what I get is this:
Error using accumarray Second input VAL must be a vector with one element for each row in SUBS, or a scalar.
Error in Sysmodel (line 69) APload=accumarray(index(t), Userload(t), [max(index) 1])';
Assuming A and B are still row vectors, try this:
t = A>0;
C = accumarray(A(t)',B(t)')';
Thanks Greg and Roger. I removed elements containing zeros and then used method suggested by Greg.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 14 Apr. 2015

Bearbeitet:

am 15 Apr. 2015

Community Treasure Hunt

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

Start Hunting!

Translated by