필터 지우기
필터 지우기

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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by