Problem with multiple accesses in array indexing

Hi everybody,
I have problems to make calculations on arrays with multiple accesses to the same indexes. For instance, if I have a simple vector
A = [7,8,9]
and I would like to make calculations several times on the same index
A([1,1]) = A([1,1]) + 1
the results shoud be equal to 9 and not to 8 (in tis case, I would like to make the computation twice). The only way I found to do this is with a simple statement :
b = [1,1];
for k = 1:length(b)
A(b(k)) = A(b(k)) +1;
end
But that is not cheap with big arrays. So, I would be pleased to know what is the solution of this.
Thank you guys.

1 个评论

Hi,
I think you need to give a more complicated example, because in this case, you could just do:
A(b)=A(b)+length(b);
But I'm guessing that may not generalize to your real problem...

请先登录,再进行评论。

回答(2 个)

Like AC, I think that your example is too easy to give you a solution.
But I'm going to try with some supoositions.
For me
b = [ 1 1 2 2 3 1 2 3 ];
A = [ 7 8 9 ];
and you add "a" and not 1.
So (I can't make the test but ...)
[ c, ib,ic ] = unique( b )
V = arrayfun( @(D) sum( ic == D ), [ 1 : max(ic) ] );
A = A + V * a ;
but I'm not sure for the creation of V.

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by