Does Matlab / Octave support slicing operations?

I am new to Octave / Matlab, so still I know you can apply a matrix operation (for example *) or a cell operation (for example .*).

Now I have a problem that lies between these two modes.

For example (this is just an 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 a vector to them. So add a vector to the first column, add a vector to the second column, .... add a vector to the last column. And as a result, of course, we obtain the matrix (10,10).

So far I have come up with two approaches:

  • loop over columns and add vector

  • repeat the vector, and then add the entire repeating vector (so now it's really a matrix) to the matrix

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

QUESTION - is there any pleasant third way, the cutoff mode? In which I could say, look at the matrix as fragments, add a vector to the slices and drop this view and process the matrix as usual?

+3
source share
1 answer

You can use Matlab bult in binary-singleton-expand ( bsxfun ) to achieve the desired results in memory.

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

This will give the following conclusion

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

repmat ( ), . . bsxfun versus repmat

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

, , , . sparse,

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

bsxfun .

+5

All Articles