フィルターのクリア

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

1 回表示 (過去 30 日間)
Sujan
Sujan 2013 年 1 月 16 日
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 ?

採用された回答

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

その他の回答 (1 件)

Image Analyst
Image Analyst 2013 年 1 月 16 日
編集済み: Image Analyst 2013 年 1 月 16 日
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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by