Brendan
Brendan

Reputation: 19353

Can I store a MATLAB slice in a variable?

I have a lengthy slice sequence that I need to apply to lots of MATLAB matrices. How can I do this?

i.e. can I simplify,

y(1:some_var*3,1:some_other_var*3,1:another_var*3) = x1(1:some_var*3,1:some_other_var*3,1:another_var*3) .* x2(1:some_var*3,1:some_other_var*3,1:another_var*3) ./ x3(1:some_var*3,1:some_other_var*3,1:another_var*3)

to something like,

inds = slice(1:some_var*3,1:some_other_var*3,1:another_var*3)
y(inds) = x1(inds) .* x2(inds) ./ x3(inds)

like I can do in Python?

Upvotes: 3

Views: 342

Answers (2)

gnovice
gnovice

Reputation: 125854

One option is to store each vector of indices in a cell of a cell array, then extract the cell array content as a comma-separated list like so:

inds = {1:some_var*3, 1:some_other_var*3, 1:another_var*3};
y(inds{:}) = x1(inds{:}) .* x2(inds{:}) ./ x3(inds{:});

If you have large matrices, with relatively small/sparse sets of indices, this may be more efficient than using a logical mask as Amro suggested.

Upvotes: 2

Amro
Amro

Reputation: 124563

In your case, you can create a logical mask:

%# assuming x1,x2,x3,y are all of the same size

mask = false(size(x1));
mask(1:some_var*3,1:some_other_var*3,1:another_var*3) = true;

y(mask) = x1(mask).*x2(mask)./x3(mask);

Other functions that you might want to read about: FIND, SUB2IND

Upvotes: 3

Related Questions