Subtract column from a matrix

조회 수: 1 (최근 30일)
Mikhail
Mikhail 2014년 9월 25일
댓글: Image Analyst 2014년 9월 26일
In matlab it is easy to subtract number from column or row. I want to subtract column [n x 1] from a matrix [n x m]. Is it possible to doit without for loop? When I wrote it just with '-', there was dimension mismatch error. Thanks.
  댓글 수: 1
Stephen23
Stephen23 2014년 9월 26일
Use bsxfun . This is exactly what it is for.

댓글을 달려면 로그인하십시오.

채택된 답변

Image Analyst
Image Analyst 2014년 9월 25일
You could use repmat() to create an array of the same size:
out = inputArray - repmat(columnVector, [1, m]);
  댓글 수: 6
Titus Edelhofer
Titus Edelhofer 2014년 9월 26일
Nice comparison!
One aspect has not been mentioned yet: for larger matrices/vectors the memoryfriendliness of bsxfun compared to repmat (which blows up the memory usage significantly).
Titus
Image Analyst
Image Analyst 2014년 9월 26일
Good point. This can be done by adding these lines into the loop:
memoryUsed = memory;
fprintf('Memory used by MATLAB = %d bytes.\n', memoryUsed.MemUsedMATLAB)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Guillaume
Guillaume 2014년 9월 25일
편집: Guillaume 2014년 9월 25일
Use bsxfun, it will expands singleton dimensions:
n = 10; m = 20;
matrix = rand(n, m);
column = rand(n, 1);
bsxfun(@minus, matrix, column)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by