简体   繁体   中英

Does Matlab/Octave support operation on matrix slices?

I am new to Octave/Matlab so so far I know, you can apply matrix operation (like * ) or cell-wise operation (like .* ).

Now I have the problem which lies between those two modes.

For example (this is just EXAMPLE ) I have a matrix (10,10) and a vector (10,1). I would like to work with this matrix in slices (in this case column slices) and add vector to them. So add vector to first column, add vector to second column, ...., add vector to last column. And in the result acquire matrix (10,10) of course.

So far I come up with two approaches:

  1. manually loop over columns, and add the vector

  2. repeat the vector and then add entire repeated vector (so now it is matrix really) to the matrix

The second one uses vectorization approach, however consumes memory a lot, in the first case, there is no vectorization approach (manual loop), but the memory is not overused.

QUESTION -- is there some nice third, way, slice mode? In which I could say, view matrix as slices, add vector to slices, and drop such view, and treat matrix as usual?

You can use Matlab's bult in binary-singleton-expansion ( bsxfun ) to achieve the results you desire in a memory efficient manner.

x = ones(10); %// 10x10 matrix
y = 1:10; %// 10x1 matrix
z = bsxfun(@plus, x, y)

This will give the following ouput

z =

 2     3     4     5     6     7     8     9    10    11
 2     3     4     5     6     7     8     9    10    11
 2     3     4     5     6     7     8     9    10    11
 2     3     4     5     6     7     8     9    10    11
 2     3     4     5     6     7     8     9    10    11
 2     3     4     5     6     7     8     9    10    11
 2     3     4     5     6     7     8     9    10    11
 2     3     4     5     6     7     8     9    10    11
 2     3     4     5     6     7     8     9    10    11
 2     3     4     5     6     7     8     9    10    11

Use of the repmat command is generally wasteful (as you pointed out in your question) and can usually be avoided. See this article for a detailed description of bsxfun versus repmat

http://blogs.mathworks.com/loren/2008/08/04/comparing-repmat-and-bsxfun-performance/

For multiplication at least, you can achieve a result using a trick involving diagonal matrices. You can use the sparse keyword to reduce the memory usage for the interim storage of the diagonal matrix

x = ones(10); %// 10x10 matrix
y = 1:10; %// 10x1 matrix
yd = sparse(diag(y)); %// 10x10 matrix, but memory is only used to store data and its indicies

z =  yd * x %// 10x10 matrix

However, the bsxfun solution is generally superior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM