Subtract column from a matrix

9 Ansichten (letzte 30 Tage)
Mikhail
Mikhail am 25 Sep. 2014
Kommentiert: Image Analyst am 26 Sep. 2014
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 Kommentar
Stephen23
Stephen23 am 26 Sep. 2014
Use bsxfun . This is exactly what it is for.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Image Analyst
Image Analyst am 25 Sep. 2014
You could use repmat() to create an array of the same size:
out = inputArray - repmat(columnVector, [1, m]);
  6 Kommentare
Titus Edelhofer
Titus Edelhofer am 26 Sep. 2014
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 am 26 Sep. 2014
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)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Guillaume
Guillaume am 25 Sep. 2014
Bearbeitet: Guillaume am 25 Sep. 2014
Use bsxfun, it will expands singleton dimensions:
n = 10; m = 20;
matrix = rand(n, m);
column = rand(n, 1);
bsxfun(@minus, matrix, column)

Kategorien

Mehr zu Mathematics finden Sie in Help Center und File Exchange

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by