How to add arrays to specific rows of a matrix in single step ?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 ?
0 Kommentare
Akzeptierte Antwort
Andrei Bobrov
am 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);
Weitere Antworten (1)
Image Analyst
am 16 Jan. 2013
Bearbeitet: Image Analyst
am 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
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!