Subtract column from a matrix

8 次查看(过去 30 天)
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.

采纳的回答

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 中查找有关 Logical 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by