What wrong with the indexing code?

If I want to fill in a matrix, of which I have its indices without a for loop, how could I do it? Suppose that the (row(i),col(i)) elements to be filled are given.
value = 189;
row = [ 1 3 6 7 8 ];
col = [ 1 1 4 4 5];
B(row,col) = value

 Risposta accettata

B = full( sparse(row, col, value) );
or
B = accumarray([row(:), col(:)], value);

2 Commenti

how about using arrayfun/bsxfun or something?
Not at all easily with arrayfun or bsxfun as assignment through function calls is difficult and never less than ugly.

Accedi per commentare.

Più risposte (1)

B(sub2ind([max(row) max(col)],row,col)) = value

8 Commenti

as usual; can you explain that?
Birdman
Birdman il 8 Feb 2018
Modificato: Birdman il 8 Feb 2018
sub2ind function converts the equivalent indexes of given rows and columns and it should also know the size of your matrix. The inputs are accordingly given. For instance, the linear index representation for a matrix having 2 rows and 5 columns, the index of the element at
row=2;
col=3;
is
6
It does not solve the problem. I want B(row(i), col(i)) = value, without using a for loop.
I did not use for loop here,as you can see.
sz = [max(row), max(col)]
B(sub2ind(sz, row, col)) = value
B = reshape(B, sz)
The reshape() is not needed.
Doesn't my answer also work Walter?
it did not :/

Accedi per commentare.

Prodotti

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by