Borrar filtros
Borrar filtros

How to add arrays to specific rows of a matrix in single step ?

1 visualización (últimos 30 días)
Suppose I have a matrix A of size (k x n).
I want to add an array of size (1 x n) to some of the rows of this matrix, say rows (2,5,7,9).
How can this be done in single step ?

Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 16 de En. de 2013
a = randi(9, 10, 4);
b = 100*ones(1, 4);
rs = [2 5 7 9];
a(rs,:) = bsxfun(@plus,a(rs,:),b);

Más respuestas (1)

Image Analyst
Image Analyst el 16 de En. de 2013
Editada: Image Analyst el 16 de En. de 2013
Try this demo:
% Define sample data.
a = randi(9, 10, 4)
b = 100*ones(1, 4)
% Define the rows to add b to:
rowsToAddTo = [2 5 7 9]
% Do the addition:
a(rowsToAddTo, :) = a(rowsToAddTo, :) + repmat(b, [length(rowsToAddTo), 1])
In the command window
a =
2 9 7 8
6 5 8 7
5 4 9 8
8 6 5 3
1 4 4 7
6 3 8 8
3 2 8 3
6 4 5 5
2 5 1 6
4 9 3 6
b =
100 100 100 100
rowsToAddTo =
2 5 7 9
a =
2 9 7 8
106 105 108 107
5 4 9 8
8 6 5 3
101 104 104 107
6 3 8 8
103 102 108 103
6 4 5 5
102 105 101 106
4 9 3 6

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by