This is a question about incrementing one value of a MATLAB array multiple times in the same statement, without having to use a for loop.
I set my array as:
>> A = [10 20 30];
And then run:
>> A([1, 1]) = A([1, 1]) + [20 3]
A =
13 20 30
Clearly the 20 is ignored. However, i would like it to be included, so that:
>> A = [10 20 30];
>> A([1, 1]) = A([1, 1]) + [20, 3]
would give:
A =
33 20 30
Is there a function to allow this to be done in a nice, vectorised fashion?
(In reality, the indexing to the array would include multiple indexes, so it could be [1 1 2 2 1 1 1 1 3 3 3]
etc., with an array of numbers to increment by (the [20, 3]
above) of the same length.)
Maybe there's something I don't quite get here, but you're basically trying to add 23 to the first element of A, right? So you can write:
Also, if you have an index array, you can write
What you want to do can be done using the function ACCUMARRAY, like so:
And the output of this example should be:
EDIT: If
A
is a large array of values, and there are just a few increments to add, the following may be more computationally efficient than the above: