Effacer les filtres
Effacer les filtres

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

1 vue (au cours des 30 derniers jours)
Sujan
Sujan le 16 Jan 2013
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 ?

Réponse acceptée

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

Plus de réponses (1)

Image Analyst
Image Analyst le 16 Jan 2013
Modifié(e) : Image Analyst le 16 Jan 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

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by